Question

I have a class MyList that overrides the << operator to be able to log itself to the console:

class MyList {
public:
    vector<int> *numbers;
};
ostream& operator<<(ostream& os, MyList& l);

Implementation:

ostream& operator<<(ostream& os, MyList& l) {
    for (int i = 0; i < l.numbers->size(); i++) {
        os << l.numbers->at(i);         
    }
    return os;
}

In an other class I have a member variable of type MyList and I can't print it to the console. Interestingly a local MyList variable works fine:

class A {
public:
    MyList list;
    void someMethod() const;
};

Implementation:

void A::someMethod() const {
    MyList local;
    // Set up local list.
    cout << "Local:" << local; // OK!
    cout << "Member:" << list; // ERROR!
}

This is the error message:

Invalid operands to binary expression ('basic_ostream<char,
std::__1::char_traits<char>>' and 'const MyList')

Xcode's auto-fix recommends to reference list:

cout << "Member:" << &list;

This will compile, but (obviously) it prints the adress of list and not my content. I don't understand what the difference is between those two variables in regards to the << operator. Could anybody explain?

Was it helpful?

Solution

I don't think this is your real code, but here's my guess:

ostream& operator<<(ostream& os, const MyList& l)
//                                 |
//                             note const

Either that, or something really dumb like forgetting a trailing ;:

class A {
public:
    MyList list;
    void someMethod();
};  // <------- here

OTHER TIPS

It seems, you omitted a const in several places: As it stands, your code should be OK. However, if you have a const member function, the members are const and you can't bind a non-const reference to a const object. Thus, output operators are normally declared to take a const& as second argument:

std::ostream& operator<< (std::ostream& os, MyList const& l) {
    ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top