Che*_*Toy 8 c++ iostream operator-overloading
有没有办法重载<<运算符,作为类成员,将值作为文本流打印.如:
class TestClass {
public:
ostream& operator<<(ostream& os) {
return os << "I'm in the class, msg=" << msg << endl;
}
private:
string msg;
};
int main(int argc, char** argv) {
TestClass obj = TestClass();
cout << obj;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法是在类之外重载操作符:
ostream& operator<<(ostream& os, TestClass& obj) {
return os << "I'm outside of the class and can't access msg" << endl;
}
Run Code Online (Sandbox Code Playgroud)
但是,访问对象的私有部分的唯一方法是与操作员函数联系,如果可能的话,我宁愿避开朋友,因此请求您提供替代解决方案.
有关如何继续的任何意见或建议将有所帮助:)
Mik*_*our 10
它必须是非成员,因为类形成运算符的第二个参数,而不是第一个参数.如果输出只能使用公共接口完成,那么就完成了.如果它需要访问非公开成员,那么你必须宣布它为朋友; 这就是朋友的作用.
class TestClass {
public:
friend ostream& operator<<(ostream& os, TestClass const & tc) {
return os << "I'm a friend of the class, msg=" << tc.msg << endl;
}
private:
string msg;
};
Run Code Online (Sandbox Code Playgroud)
我相信一种流行的方式是非会员,非朋友免费operator<<,print在您的班级中调用公共非虚拟方法.此打印方法可以执行工作或委托给受保护的虚拟实现.
class TestClass {
public:
ostream& print(ostream& os) const {
return os << "I'm in the class, msg=" << msg << endl;
}
private:
string msg;
};
ostream& operator<<(ostream& os, TestClass& obj) {
return obj.print(os);
}
int main(int argc, char** argv) {
TestClass obj;
cout << obj;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15000 次 |
| 最近记录: |