Ridley Nelson
Ridley Nelson

Reputation: 71

C++ how do i override the << operator within a class

How would i override the << operator within a class? Or be able to print a vector<byte> from within a class. My current code looks like

ostream& operator<<(ostream& os, const vector<byte>& bytes)
{
    if (bytes.size() == 0)
        return os;

    for (size_t i = 0; i < bytes.size()-1; i++)
        os << hex << (int)bytes[i] << " ";
    os << bytes.back();
    return os;
}

It’s hanging outside of the class, and only functions outside of the class can cout << and print a vector<byte>. I want to be able to print one from within the class.

Edit 1

I saw some confusion in the part where i sort of mention how i use it, here would be a good example

# method 1
ostream& operator<<(ostream& os, const vector<byte>& bytes)
{
    if (bytes.size() == 0)
        return os;

    for (size_t i = 0; i < bytes.size()-1; i++)
        os << hex << (int)bytes[i] << " ";
    os << bytes.back();
    return os;
}

int main( {
    vector<byte> v = something;
    cout << “Vector Example: ” << v << endl;
}

I want to have the top method 1 in a class, but per some comments, it is impossible. Is there a different way?

Edit 2

Thought I’d share my revised and working code thanks to @StephanH.

#include <vector>
#include <fstream>
#include <cstddef>
#include <iostream>
#include <iomanip>
#include <string>

std::ostream& operator<<(std::ostream& os, const std::vector<std::byte>& bytes)
{
    if (bytes.size() == 0)
        return os;

    for (size_t i = 0; i < bytes.size() - 1; i++)
        os << std::hex<< (int)bytes[i] << " ";
    os << int(bytes.back());
    return os;
}

class MClass
{
    public:
        std::vector<std::byte> smth;

        friend std::ostream& operator<<(std::ostream& stream, const MClass& obj) {
            std::string ascii = "hello";
            std::vector<std::byte> bytes(ascii.length());
            for (size_t i = 0; i < ascii.length(); i++)
            {
                bytes[i] = static_cast<std::byte>(ascii[i]);
            }

            return stream << bytes;
        }
};

int main() {
    MClass m;
    std::cout<<m;
}

Still trying to figure out how to print out whe i do m.smth

Upvotes: 0

Views: 107

Answers (1)

StephanH
StephanH

Reputation: 470

it is not really sure what you want to achieve and in what context your are in. Here is my approach

#include <vector>
#include <fstream>
#include  <cstddef>
#include <iostream>
#include <iomanip>

std::ostream& operator<<(std::ostream& os, const std::vector<std::byte>& bytes)
{
    if (bytes.size() == 0)
        return os;

    for (size_t i = 0; i < bytes.size() - 1; i++)
        os << std::hex<< (int)bytes[i] << " ";
    os << int(bytes.back());
    return os;
}

class MClass
{
    std::vector<std::byte> smth;

    friend std::ostream& operator<<(std::ostream& stream, const MClass& obj) {
        return stream << obj.smth;
    }
};

Upvotes: 1

Related Questions