假设T
是一个C ++类,如果我T a = b;
,是复制构造函数还是赋值运算符?
我当前的实验显示复制构造函数被调用,但不明白为什么。
#include <iostream>
using namespace std;
class T {
public:
// Default constructor.
T() : x("Default constructor") { }
// Copy constructor.
T(const T&) : x("Copy constructor") { }
// Assignment operator.
T& operator=(const T&) { x = "Assignment operator"; }
string x;
};
int main() {
T a;
T b = a;
cout << "T b = a; " << b.x << "\n";
b = a;
cout << "b = a; " << b.x << "\n";
return 0;
}
$ g++ test.cc
$ ./a.out
T b = a; Copy constructor
b = a; Assignment operator
谢谢!
答案 0 :(得分:6)
调用复制构造函数是因为
T a = b;
与
具有相同的效果T a(b);
这是初始化,而不是作业。长话短说,这就是语言的运作方式。
答案 1 :(得分:2)
...
// The variable a does not exist before this point, therefore it is *conststructed*
T a = b; // Copy constructor is called
...
VS
...
T a; // Default constructor is called
// a already exists, so assignment is used here
a = b; // assignment operator is called
...