重载 operator<< 的含义及作用

7

可能是重复问题:
运算符重载

我在这个主题中没有找到任何有助于我的东西…… 我正在尝试重载 << 运算符,这是我的代码:

 ostream& Complex::operator<<(ostream& out,const Complex& b){
    out<<"("<<b.x<<","<<b.y<<")";
    return out;
}    

这是H文件中的声明:

 ostream& operator<<(ostream& out,const Complex& b);

我遇到了这个错误: error: std::ostream& Complex::operator<<(std::ostream&, const Complex&) must take exactly one argument 我做错了什么,有什么原因吗? 谢谢。
3个回答

10

在您的情况下,operator << 应该是一个自由函数(free function),而不是 Complex 类成员。

如果您将 operator << 定义为类成员,它实际上应该带有一个参数,即 stream。但这样做会使您无法像下面这样编写:

std::cout << complex_number;

但是

complex_number << std::cout;

相当于

complex_number. operator << (std::cout);

正如您所了解的那样,这不是常见的做法,这就是为什么 operator << 通常被定义为自由函数。


2
那个免费函数通常会成为您对象的 friend - AJG85

1
class Complex
{
    int a, b;
public:
    Complex(int m, int d)
    {
        a = m; b = d;
    }
    friend ostream& operator<<(ostream& os, const Complex& complex);
};

ostream& operator<<(ostream& os, const Complex& complex)
{
    os << complex.a << '+' << complex.b << 'i';
    return os;
}

int main()
{
    Complex complex(5, 6);
    cout << complex;
}

更多信息在这里


3
它不能同时既是朋友又是成员。 - Bo Persson
@BoPersson 重写了答案。 - zar

0
如前所述,流重载需要是自由函数,定义在类外部。
个人而言,我更喜欢避免使用友元关系,而是重定向到公共成员函数:
class Complex
{
public:
   std::ostream& output(std::ostream& s) const;
};

std::ostream& operator<< (std::ostream& s, const Complex& c)
{
   return c.output(s);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接