什么时候调用复制赋值运算符?
When is the copy assignment operator called?
当我读到复制构造函数和复制赋值构造函数时,我的理解是两者都将它们的属性传递给另一个,并且它们都由编译器隐式声明(如果未定义)。所以无论做有用与否,两者都必须存在。
然后我测试了这段代码:
#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"?
没有复制赋值运算符只是复制构造函数。它打印出:
// Default constructor
// Copy constructor
// Copy constructor # Why it's printed out even though I didn't define it?
没有复制构造函数只是复制赋值运算符。它打印出:
// Default constructor # Why "Copy assignment operator" is not printed out?
只有构造函数。它打印出:
// Default constructor # Understandable
所以,就好像编译器根本不关心我是否定义了复制赋值运算符。上面四个例子中的 None 打印出 "Copy assignment operator"。那么它是什么时候被调用的,它是否真的存在并且有意义?
Test c = b
是初始化,不是赋值。
如果你这样做了:
Test c;
c = b;
那么它会调用复制赋值运算符。
当我读到复制构造函数和复制赋值构造函数时,我的理解是两者都将它们的属性传递给另一个,并且它们都由编译器隐式声明(如果未定义)。所以无论做有用与否,两者都必须存在。
然后我测试了这段代码:
#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"?
没有复制赋值运算符只是复制构造函数。它打印出:
// Default constructor // Copy constructor // Copy constructor # Why it's printed out even though I didn't define it?
没有复制构造函数只是复制赋值运算符。它打印出:
// Default constructor # Why "Copy assignment operator" is not printed out?
只有构造函数。它打印出:
// Default constructor # Understandable
所以,就好像编译器根本不关心我是否定义了复制赋值运算符。上面四个例子中的 None 打印出 "Copy assignment operator"。那么它是什么时候被调用的,它是否真的存在并且有意义?
Test c = b
是初始化,不是赋值。
如果你这样做了:
Test c;
c = b;
那么它会调用复制赋值运算符。