从函数“operator=”返回有什么区别
by reference
by value
? 在下面的示例中,这两个版本似乎都产生了正确的结果。
#include <iostream>
using namespace std;
class CComplexNumber{
float m_realPart;
float m_imagPart;
public:
CComplexNumber(float r,float i):m_realPart(r),m_imagPart(i){}
//the following can be also
//CComplexNumber& operator=(const CComplexNumber& orig){
CComplexNumber operator=(const CComplexNumber& orig){
if (this!=&orig){
this->m_realPart=orig.m_realPart;
this->m_imagPart=orig.m_imagPart;
}
return *this;
}
friend ostream& operator<<(ostream& lhs,CComplexNumber rhs){
lhs<<"["<<rhs.m_realPart<<","<<rhs.m_imagPart<<"]"<<endl;
}
};
int main() {
CComplexNumber a(1,2);
CComplexNumber b(3,4);
CComplexNumber c(5,6);
a=b=c;
cout<<a<<b<<c;
return 0;
}