我有一个覆盖 <<
的类 MyList运算符(operator)能够将自己登录到控制台:
class MyList {
public:
vector<int> *numbers;
};
ostream& operator<<(ostream& os, MyList& l);
实现:
ostream& operator<<(ostream& os, MyList& l) {
for (int i = 0; i < l.numbers->size(); i++) {
os << l.numbers->at(i);
}
return os;
}
在另一个类中,我有一个 MyList 类型的成员变量,但我无法将它打印到控制台。有趣的是,本地 MyList 变量工作正常:
class A {
public:
MyList list;
void someMethod() const;
};
实现:
void A::someMethod() const {
MyList local;
// Set up local list.
cout << "Local:" << local; // OK!
cout << "Member:" << list; // ERROR!
}
这是错误信息:
Invalid operands to binary expression ('basic_ostream<char,
std::__1::char_traits<char>>' and 'const MyList')
Xcode的自动修复建议引用list
:
cout << "Member:" << &list;
这将编译,但(显然)它打印了 list
的地址而不是我的内容。我不明白这两个变量在 <<
方面有什么区别?运算符(operator)。谁能解释一下?
最佳答案
我认为这不是您的真实代码,但这是我的猜测:
ostream& operator<<(ostream& os, const MyList& l)
// |
// note const
要么那样,要么像忘记尾随 ;
这样非常愚蠢的事情:
class A {
public:
MyList list;
void someMethod();
}; // <------- here
关于c++ - 控制台输出的覆盖运算符 << 不适用于成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13521752/