[英]std::ostream Composition of Classes
We have the following situation:我们有以下情况:
In Classes A and B, we have overridden the <<
operator.在 A 类和 B 类中,我们覆盖了
<<
运算符。
Now, we have a new class C with data members of objects of A and B.现在,我们有一个新的类 C,其中包含 A 和 B 对象的数据成员。
How would we override the <<
operator here?我们将如何在这里覆盖
<<
运算符?
To be more specific, We need something like this:更具体地说,我们需要这样的东西:
cout<<objectOfC
corresponds to cout<<correspondingObjectOfA<<correspondingObjectOfB
cout<<objectOfC
对应cout<<correspondingObjectOfA<<correspondingObjectOfB
I'm not getting how to modify the ostream& object so as to return it back.我不知道如何修改 ostream& 对象以将其返回。
ostream& operator<< (ostream& out, const C& obj){ // This is a friend function declared in C.h
A* a = obj.AObject; // Returns the corresponding object of A
B* b = obj.BObject; // Returns the corresponding object of B
// Need to modify out somehow to 'cout' A and B respectively when cout is called on an object of C
return out;
}
Any help would be greatly appreciated.任何帮助将不胜感激。 Thank you :)
谢谢 :)
If you already have appropriate overrides for A
and B
, just use them.如果您已经有适当的
A
和B
覆盖,只需使用它们。
ostream& operator<< (ostream& out, const C& obj) {
out << *obj.AObject << *obj.BObject;
return out;
}
Because operator<<
returns its ostream
argument, you can further condense this:因为
operator<<
返回它的ostream
参数,你可以进一步压缩这个:
ostream& operator<< (ostream& out, const C& obj) {
return out << *obj.AObject << *obj.BObject;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.