操作员<< overloading ostream [duplicate]

问题描述 投票:0回答:3

为了这样使用 cout :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;
}

谢谢

c++ overloading operator-keyword ostream
3个回答
6
投票

您不会向

ostream
添加另一个成员函数,因为这需要重新定义类。您无法将其添加到
myClass
,因为
ostream
首先出现。您唯一能做的就是向独立函数添加重载,这就是您在示例中所做的。


2
投票

仅当它是类的成员函数时才为第一个参数。因此,它将是:

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

由于

ostream
是在上课之前很久就写的,所以你会看到将课程放在那里的问题。因此,我们必须将运算符实现为独立函数:

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

当运算符作为类的成员函数实现时,左侧为

this
,参数变为右侧。 (对于二元运算符 - 一元运算符的工作原理类似。)


-1
投票

因为您重载的是自由函数,而不是成员函数。

© www.soinside.com 2019 - 2024. All rights reserved.