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