当我读到有关复制构造函数和复制赋值构造函数的内容时,我理解的是两者都将它们的属性彼此放弃,并且它们都是由编译器隐式声明的(如果没有定义)。因此,无论是否有用,都必须存在。
然后我测试了这段代码:
#include <iostream>
using namespace std;
class Test {
public:
Test () {
cout << "Default constructor" << endl;
}
Test (const Test& empty) {
cout << "Copy constructor" << endl;
}
Test& operator=(const Test& empty) {
cout << "Copy assignment operator" << endl;
}
private:
};
int main () {
Test a; // Test default constructor
Test b (a); // Test copy constructor
Test c = b; // Test copy assignment constructor
system ("pause");
return 0;
}
但似乎根本没有调用复制赋值运算符。我尝试了三个条件:
包括所有内容。打印出来:
// Default constructor
// Copy constructor
// Copy constructor # Why not prints out "Copy assignment operator"?
Whitout复制赋值运算符只是复制构造函数。打印出来:
// Default constructor
// Copy constructor
// Copy constructor # Why it's printed out even though I didn't define it?
Whitout复制构造函数只是复制赋值运算符。打印出来:
// Default constructor # Why "Copy assignment operator" is not printed out?
只有构造函数。打印出来:
// Default constructor # Understandable
所以,就像编译器甚至不关心我是否定义了复制赋值运算符一样。以上四个示例中没有一个打印出“复制赋值运算符”。那么它什么时候被调用,如果它确实存在并具有意义?
答案 0 :(得分:14)
Test c = b
是初始化,而不是作业。
如果你这样做了:
Test c;
c = b;
然后它会调用复制赋值运算符。