当调用 [abc e = a+b] 时,不会调用复制构造函数。
class abc{
int i;
public:
abc()
{
i = 10;
cout<<"constructor"<<endl;
}
abc(const abc &a)
{
cout<<"copy constructor"<<endl;
i = a.i;
}
abc operator=(const abc &a)
{
cout<<"operator="<<endl;
abc temp;
temp.i = a.i;
return temp;
}
abc operator+(abc& a)
{
cout <<"Operator+ called"<<endl;
abc temp;
temp.i = i+a.i;
return temp ;
}
};
int main()
{
abc a,b;
cout <<"----------------------------------------------"<<endl;
a = b;
cout <<"----------------------------------------------"<<endl;
abc c = a;
cout <<"-----------------------------------------------"<<endl;
abc d(a);
cout <<"-------------------------------------------"<<endl;
**abc e = a+b;**
}
但是,如果将重载运算符方法替换为以下返回对 abc 类对象的引用的方法,则会调用复制构造函数。
abc& operator=(const abc &a)
{
cout<<"operator="<<endl;
i = a.i;
return *this;
}
abc& operator+(const abc& a)
{
cout <<"Operator+ called"<<endl;
i = i+a.i;
return *this ;
}
有人可以解释为什么会这样吗?