有人可以在下面的示例代码中进行解释:
为什么既不调用构造函数也不调用赋值运算符。
为什么在类的+运算符中创建的对象在运算符调用结束后没有被破坏,而是分配给了c3。
示例代码:
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {cout<<"Constructor"<<endl; real = r; imag = i;}
Complex(Complex const &obj) {
cout<<"Copy Constructor"<<endl;
real = obj.real;
imag = obj.imag;
}
~Complex() {
cout<<"Destructor"<<endl;
}
Complex operator + (Complex const &obj) {
cout<<"Operator +"<<endl;
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void operator = (Complex const &obj)
{
cout<<"Operator ="<<endl;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
输出:
Constructor Constructor Operator + Constructor 12 + i9 Destructor Destructor Destructor