以一个具体例子进行说明,在程序中加断点调试和观察:
class complex {
public:
complex(double r = 0., double i = 0.) :real(r), image(i) { cout << "构造" << endl; }
complex(complex&c) :real(c.real), image(c.image) { cout << "复构" << endl; }
~complex() { cout << "析构" << endl; }
complex& operator=(const complex &c) {
if (this == &c)
return *this;
this->real = c.real;
this->image = c.image;
cout << "赋值" << endl;
return *this;
}
private:
double real, image;
};
int main() {
complex c1(1, 1), c2(2, 2), c3(3, 3);
c1 = c2 = c3;
system("pause");
return 0;
}
1.赋值返回引用
对于c1 = c2 = c3,先执行c2 = c3,返回c2的引用,再执行c1 = c2,相当于c1.operator=(c2.operator=(c3));
2.赋值返回对象,不返回引用
对于c1 = c2 = c3,先执行c2 = c3,即c2.operator=(c3)
返回的是c2的copy(临时对象),再执行c1 = (c2的copy),返回的是c1的copy(临时对象),执行完毕后,最后程序会自动调用析构函数把2个临时对象释放掉。
上述虽然也完成了连续赋值,但是开销太大,创建和最后释放c1的copy和c2的copy,相比于返回引用额外多调用了2次复构函数和2次析构函数。
对于(c1 = c2) = c3,最后c1的结果是不会和c3相同的,原因如下:先执行c1 = c2,返回的是c1的copy(临时对象),再执行(c1的copy) = c3,相当于执行(c1的copy).operator=(c3)
,返回的又是一个新的临时对象(由c1的copy产生的新copy)。所以最终c1的结果是不可能和c3相同的。代码如下:
class complex {
public:
complex(double r = 0., double i = 0.) :real(r), image(i) { cout << "构造" << endl; }
complex(complex&c) :real(c.real), image(c.image) { cout << "复构" << endl; }
~complex() { cout << "析构" << endl; }
complex operator=(const complex &c) {
if (this == &c)
return *this;
this->real = c.real;
this->image = c.image;
cout << "赋值" << endl;
return *this;
}
private:
double real, image;
};
int main() {
complex c1(1, 1), c2(2, 2), c3(3, 3);
(c1 = c2) = c3;
system("pause");
return 0;
}
综上所述,operator= 要返回引用,可以省去很多不必要的麻烦!