小编Ano*_*123的帖子

获取错误:尽管重载了 << 运算符,但仍不匹配 'operator<<'(操作数类型为 'std::basic_ostream<char>' 和 'Complex')

我是一名新手程序员,我正在编写一个简单的程序,将两个复数相加。我<<以以下方式超载:

ostream& operator << (ostream& output, Complex &complex_num){

        output << complex_num.realPart << " + " << "(" << complex_num.imaginaryPart << ")i" <<endl;
        return output;

    }
Run Code Online (Sandbox Code Playgroud)

我的加法函数如下:

Complex operator +(Complex &c2){
        Complex temp;
        temp.realPart=realPart+c2.realPart;
        temp.imaginaryPart=imaginaryPart + c2.imaginaryPart;
        return temp;
    }
Run Code Online (Sandbox Code Playgroud)

在我的主函数中,当我尝试通过键入以下内容来打印结果时:

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num1 + num2<< endl; 
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息,说与 operator 不匹配<<。但是,当我分配另一个对象num3 = num1 + num2然后编写以下代码时,程序运行良好。

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num3<< endl; 
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?谁能帮帮我吗?

c++ overloading stream operator-keyword

2
推荐指数
1
解决办法
606
查看次数

标签 统计

c++ ×1

operator-keyword ×1

overloading ×1

stream ×1