operator <<重载ostream

Jes*_*ess 6 c++ overloading ostream operator-keyword

为了使用cout:std :: cout << myObject,为什么我必须传递一个ostream对象?我认为这是一个隐含的参数.

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

    out << o.fname << " " << o.lname;
    return out;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Dav*_*ley 6

您没有添加其他成员函数ostream,因为这将需要重新定义类.你不能把它添加到myClass,因为ostream先行.你唯一能做的就是为一个独立的函数添加一个重载,这就是你在这个例子中所做的.