请帮助!得到错误:尽管重载了<

问题描述 投票:0回答:1
却没有匹配'operator 我是一名新手程序员,我正在编写一个简单的程序,将两个复数相加。我已经通过以下方式重载了<ostream& operator << (ostream& output, Complex &complex_num){ output << complex_num.realPart << " + " << "(" << complex_num.imaginaryPart << ")i" <<endl; return output; }

我的附加功能如下:

Complex operator +(Complex &c2){
        Complex temp;
        temp.realPart=realPart+c2.realPart;
        temp.imaginaryPart=imaginaryPart + c2.imaginaryPart;
        return temp;
    }

在我的主要功能中,当我尝试通过输入来打印结果时:

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num1 + num2<< endl; 

我收到一个错误消息,说运算符“ <

cout << "ADDITION OF THE TWO COMPLEX NUMBERS: "<<num3<< endl; 

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

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

您的operator+返回一个Complex,它是一个临时对象。当与operator<<一起使用时,它不起作用,因为您正试图将其绑定到非常量引用参数。

变量可以绑定到非常量引用,这样就可以工作。

解决方法是通过const引用将参数传递给operator<<

ostream& operator << (ostream& output, Complex const &complex_num);
c++ stream overloading operator-keyword
1个回答
1
投票

您的operator+返回一个Complex,它是一个临时对象。当与operator<<一起使用时,它不起作用,因为您正试图将其绑定到非常量引用参数。

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