operator<< overloading ostream

江枫思渺然 提交于 2019-12-04 03:27:06

问题


In order to use cout as such : std::cout << myObject, why do I have to pass an ostream object? I thought that was an implicit parameter.

ostream &operator<<(ostream &out, const myClass &o) {

    out << o.fname << " " << o.lname;
    return out;
}

Thanks


回答1:


You aren't adding another member function to ostream, since that would require redefining the class. You can't add it to myClass, since the ostream goes first. The only thing you can do is add an overload to an independent function, which is what you're doing in the example.




回答2:


Only if it is a member function of the class that would otherwise be the first argument. Thus, it would be:

class ostream {
    ...
    ostream &operator << (const myClass &o);
    ...
};

Since ostream was written long before your class, you see the problem of getting your class in there. Thus, we must implement the operator as a freestanding function:

(return type) operator << ( (left hand side), (right hand side) );

When operators are implemented as member-functions of classes, the left hand side is this, and the argument becomes the right hand side. (For binary operators - unary operators work similarly.)




回答3:


Because you are overloading a free function, not a member function.



来源:https://stackoverflow.com/questions/4347820/operator-overloading-ostream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!