shogitai
shogitai

Reputation: 1961

Finding the mistake in C++ operator overloading

I am trying to understand how to overload the '<<' operator. So i wrote a simple test code that I report part of if here:

class Buffer {

    vector<char> buffer;

    ...

    ostream& operator<< (ostream& out, const vector<char>& v) {
            out << "[";
            size_t last = v.size() - 1;
            for(size_t i = 0; i < v.size(); ++i) {
                out << v[i];
                if (i != last)
            out << ", ";
            }
            out << "]";
            return out;
    }

    ...

};

The way I use the class in the main is the usual but I get the following error. Why?

main.cpp:22:10: error: overloaded 'operator<<' must be a binary operator (has 3 parameters)
ostream& operator<< (ostream& out, const vector<char>& v) {
         ^

Upvotes: 0

Views: 89

Answers (2)

Bas in het Veld
Bas in het Veld

Reputation: 1312

It needs to be a binary operator: Since you're adding the operator as a class member, it'll always be called on a instance of that class, like this:

Buffer myBuffer;
const vector<char> myVector;
myBuffer << myVector;

You should see this as a function equivalent to:

myBuffer.DoOperator(myVector);

.. which takes only one argument, not two! So you should skip the first argument!

Upvotes: 1

Oliv
Oliv

Reputation: 18041

class Buffer {

vector<char> buffer;

...
friend
ostream& operator<< (ostream& out, const Buffer& b) {
        const vector<char>& v=b.buffer;
        out << "[";
        size_t last = v.size() - 1;
        for(size_t i = 0; i < v.size(); ++i) {
            out << v[i];
            if (i != last)
        out << ", ";
        }
        out << "]";
        return out;
}

...

};

Upvotes: 1

Related Questions