Mas*_*gol 8 c++ copy-assignment
当我读到有关复制构造函数和复制赋值构造函数的内容时,我理解的是两者都将它们的属性相互给出,并且它们都是由编译器隐式声明的(如果没有定义).因此,无论是否有用,都必须存在.
然后我测试了这段代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但似乎根本没有调用复制赋值运算符.我尝试了三个条件:
一切都包括在内.打印出来:
// Default constructor
// Copy constructor
// Copy constructor # Why not prints out "Copy assignment operator"?
Run Code Online (Sandbox Code Playgroud)Whitout复制赋值运算符只是复制构造函数.打印出来:
// Default constructor
// Copy constructor
// Copy constructor # Why it's printed out even though I didn't define it?
Run Code Online (Sandbox Code Playgroud)Whitout复制构造函数只是复制赋值运算符.打印出来:
// Default constructor # Why "Copy assignment operator" is not printed out?
Run Code Online (Sandbox Code Playgroud)只有构造函数.打印出来:
// Default constructor # Understandable
Run Code Online (Sandbox Code Playgroud)所以,就像编译器甚至不关心我是否定义了复制赋值运算符一样.以上四个示例中没有一个打印出"复制赋值运算符".那么它什么时候被调用,如果它确实存在并具有意义?
eml*_*lai 14
Test c = b是初始化,而不是赋值.
如果你这样做了:
Test c;
c = b;
Run Code Online (Sandbox Code Playgroud)
然后它会调用复制赋值运算符.
| 归档时间: |
|
| 查看次数: |
1605 次 |
| 最近记录: |