我读到,从重载的赋值运算符返回引用以启用运算符链接。但是如果没有那个返回,操作符链接似乎也可以工作。
有人可以对此有所了解吗?
class A
{
public:
int x,y;
char* str;
//Default Constructor
A(){}
//Constructor
A(int a, int b, char* s){
cout<<"initialising\n";
x = a;
y = b;
str = new char[10];
str = s;
}
//Destructor
~A(){}
//Overloaded assignment operator
const A& operator=(const A& obj)
{
cout<<"Invoking Assignment Operator\n";
x = obj.x;
y = obj.y;
str = new char[10];
str = obj.str;
//return *this;
}
};
ostream& operator<<(ostream& os, const A& obj)
{
os <<"X="<< obj.x<<" Y="<<obj.y<<" Str="<<obj.str<<"\n";
return os;
}
int main()
{
A c(3,4,"Object C");
cout<<c;
A d, e, f;
d = e = f = c; //Assignment operator invoked 3 times
cout<<e;
}
输出:
initialising
X=3 Y=4 Str=Object C
Invoking Assignment Operator
Invoking Assignment Operator
Invoking Assignment Operator
X=3 Y=4 Str=Object C