fat*_*ipp 7 c++ oop constructor class operator-overloading
我编写了一个简单的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;
}
};
Run Code Online (Sandbox Code Playgroud)
我在main中使用了这个类,就像这样:
int main() {
Complex a(1,5);
Complex b(5,7);
Complex c = a+b; // Statement 1
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果打印为:
Param constructor 1 5
Param constructor 5 7
plus operator 5 7
Param constructor 6 12
Run Code Online (Sandbox Code Playgroud)
我认为必须在Statement 1中使用复制构造函数,但我真的不知道调用哪一个.请告诉我哪一个,为什么?非常感谢
编译器正在忽略对复制构造函数的调用(实际上是两次调用).即使构造函数或析构函数有副作用,也允许(但不强制要求)C++ 11 Standard的第12.8/31段:
当满足某些条件时,允许实现省略类对象的复制/移动构造,即使为复制/移动操作选择的构造函数和/或对象的析构函数具有副作用.[..] 在下列情况下允许复制/移动操作(称为复制省略)的这种省略(可以合并以消除多个副本):
- 在
return具有类返回类型的函数的语句中,当表达式是具有与函数返回类型相同的cv-unqualified类型的非易失性自动对象(函数或catch子句参数除外)的名称时,通过将自动对象直接构造到函数的返回值中,可以省略复制/移动操作[...]
- 当一个未绑定到引用(12.2)的临时类对象被复制/移动到具有相同cv-nonqualified类型的类对象时,可以通过将临时对象直接构造到该对象中来省略复制/移动操作.省略的复制/移动的目标
如果编译器没有忽略对复制构造函数的调用,那么第一个将被选中两次,即具有以下签名的那个:
Complex( const Complex& other )
Run Code Online (Sandbox Code Playgroud)
原因是:
返回的值operator +是从temporary(Complex(a, b))复制初始化的,只有左值引用const才能绑定到temporaries.如果operator +像这样写的话会有所不同:
Complex operator+ (const Complex& other) {
// ...
Complex c(a, b);
return c;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,将调用第二个复制构造函数,因为c它不是const-qualified并且是一个左值,因此它可以绑定到非值的左值引用const;
对象cin main()是从rvalue复制构造的(返回的值operator +也是临时的).无论如何operator +返回其Complex对象,只要它按值返回它都是如此.因此,只要不执行复制省略,就会选择第一个复制构造函数.
如果您正在使用GCC并想要验证此行为,请尝试设置-fno-elide-constructors编译标志(Clang也支持它,但版本3.2有一个错误,我不知道它是否已修复).