我编写了一个简单的 C++ 类示例,其中包含 1 个非参数构造函数、1 个参数构造函数、2 个复制构造函数、1 个赋值运算符和 1 个加运算符。
class Complex {
protected:
float real, img;
public:
Complex () : real(0), img(0) {
cout << "Default constructor\n";
}
Complex (float a, float b) {
cout << "Param constructor" << a << " " << b << endl;
real = a;
img = b;
}
// 2 copy constructors
Complex( const Complex& other ) {
cout << "1st copy constructor " << other.real << " " << other.img << endl;
real = other.real;
img = other.img;
}
Complex( Complex& other ) {
cout << "2nd copy constructor " << other.real << " " << other.img << endl;
real = other.real;
img = other.img;
}
// assignment overloading operator
void operator= (const Complex& other) {
cout << "assignment operator " << other.real << " " << other.img << endl;
real = other.real;
img = other.img;
}
// plus overloading operator
Complex operator+ (const Complex& other) {
cout << "plus operator " << other.real << " " << other.img << endl;
float a = real + other.real;
float b = img + other.img;
return Complex(a, b);
}
float getReal () {
return real;
}
float getImg () {
return img;
}
};
我在 main 中使用了这个类,就像这样:
int main() {
Complex a(1,5);
Complex b(5,7);
Complex c = a+b; // Statement 1
system("pause");
return 0;
}
结果打印为:
Param constructor 1 5
Param constructor 5 7
plus operator 5 7
Param constructor 6 12
我认为 Statement 1 中必须使用复制构造函数,但我真的不知道调用的是哪个。请告诉我是哪一个,为什么?非常感谢