#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謝謝你,它現在有用! –