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?
I don’t think this is your real code, but here’s my guess:
Either that, or something really dumb like forgetting a trailing
;: