#include <iostream>
using namespace std;
class Test {
public:
Test() {
cout << "Default constructor called." << endl;
}
Test(Test &obj) {
cout << "copy constructor called." << endl;
}
Test& operator=(const Test &obj) {
cout << "copy assignment called." << endl;
return *this;
}
~Test() {
cout << "destructor called." << endl;
}
};
Test func(Test test) {
cout << "func called" << endl;
return test;
}
int main(int argc, char* argv[]) {
Test t1;
Test t2 = func(t1); // No matching constructor for initialization for 'Test'
return 0;
}
我正在学习C++。我写了一些测试代码来了解复制初始化和复制分配。现在我无法弄清楚为什么第二项任务不能工作。复制初始化不起作用?
拷贝构造函数签名是错误的,应该是'测试(const的测试和OBJ)'不'测试(测试和OBJ)' – Galik
编译器会告诉你响亮而明确:“类型的非const引用无效初始化'测试&'“。所以,使你的拷贝构造函数的参数成为一个const引用(这是正常的情况),它将起作用。 – Rene
@Galik谢谢你,它现在有用! –