C++赋值运算符重载,为什么要返回引用?查了许多资料,基本有两种说法:
一、c、c++赋值运算符的本意为“返回左值的引用”(左值:赋值号左面的变量而非其值)
可用以下程序段测试
int a,b=3,c=2;
(a=b)=c;
cout<<a<<endl;
对于x=y(x,y均为对象时),若不返回左值的引用,将会生成临时对象。 如果不处理x=y=z这样的表达式,也会正常(只是会调用拷贝构造函数和析构函数处理临时对象)。
二、为了进行连续赋值,即x=y=z
资料上都没有详细解释。现做分析如下:
1、赋值返回引用
x=y=z 先执行y=z,返回y的引用,执行x=y
2、赋值不返回引用
x=y=z 先执行y=z,返回用y初始化的临时对象(注意临时对象都是常对象),再执行x=y的临时对象(要求operator=(const X&) ),返回用x初始化的临时对象(此处要求拷贝构造函数必须为X(const X&) )。
所以也并非必须返回引用,返回引用的好处既可以于赋值的原始语义已知,又可避免拷贝构造函数和析构函数的调用。
以下程序中,可以去掉红色部分的任一处,或全部去掉以做测试。
#include <iostream>
#include <cstring>
using namespace std;
class String{
char *str;
public:
String(){str=NULL;}
String(char *s){str=new char[strlen(s)+1];strcpy(str,s);}
String(const String &s){str=new char[strlen(s.str)+1];strcpy(str,s.str);}
String &operator=(const String &s)
{
if(this==&s) return *this;
delete []str;
str=new char[strlen(s.str)+1];strcpy(str,s.str);
return *this;
}
~String(){delete []str;}
friend ostream& operator<<(ostream& out,const String &s);
};
ostream& operator<<(ostream& out,const String &s)
{
out<<s.str;
return out;
}
int main()
{
String s1,s2,s3("qweqwe");
s1=s2=s3;
cout<<s1<<endl;
return 0;
}