简体   繁体   中英

std::ostream Composition of Classes

We have the following situation:

In Classes A and B, we have overridden the << operator.
Now, we have a new class C with data members of objects of A and B.
How would we override the << operator here?

To be more specific, We need something like this:
cout<<objectOfC corresponds to cout<<correspondingObjectOfA<<correspondingObjectOfB

I'm not getting how to modify the ostream& object so as to return it back.

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.

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:

ostream& operator<< (ostream& out, const C& obj) {
    return out << *obj.AObject << *obj.BObject;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM