假设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
谢谢!
之所以调用复制构造函数是因为
T a = b;
与...具有相同的效果
T a(b);
这是初始化,而不是分配。长话短说,这就是语言的工作方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句