OS X EI Capitan [10.11.6]
Xcode [8.0]
C++
代码:
#include<iostream>
#include<math.h>
#include"MyComplex.h"
usingnamespacestd;
int main(int argc,constchar * argv[]) {
// insert code here...
MyComplex c1;
MyComplex c2;
cin >> c1;
c2 = c1;
cout << c1 <<endl;
cout << c2 <<endl;
MyComplex c3;
c3 = c1+c2;//error1:No viable overloaded '='
cout << c1+c2 << Lendl;//error2: No matching constructor for initialization of 'MyComplex'
cout << c1-c2 << Lendl;//error
cout << c1/c2 << Lendl;//error
cout << c1*c2 << Lendl;//error
return0;
}
那么对于=的重载是如何定义的呢?请看代码。
MyComplex&operator = (MyComplex &rhs){
real = rhs.getReal();
imaginary = rhs.getImaginary();
return *this;
}
看起来并没有什么问题。通过查阅 http://www.cplusplus.com/forum/general/153830/ 找到了错误原因:
Peter87大神说:A temporary object can't bind to a non-const reference.
(临时对象不能与非常量引用绑定,也就是说,绑定的引用必须是常量)
因此,重载=函数的形参必须是const。(如此隐蔽的错误真是欲哭无泪。。。)
加了const后error1消失:
MyComplex&operator = (constMyComplex &rhs){
real = rhs.getReal();
imaginary = rhs.getImaginary();
return *this;
}
error2也是同样的错误原因。
friend ostream&operator<<(ostream& os,const MyComplex &c);
const是非常重要的!要的!的!!!
改完后error都消失了