我的第一個評論,我建議刪除所有*
s和new
。
因此,主要功能變成:
int main()
{
Directory dir = Directory("alex");
Directory dir2;
dir2 = dir; // <-- fixed, original was: dir = dir2;
cout<<"done"<<endl;
return 0; // <-- fixed, return is strictly recommended for every non-void function
}
編譯...
錯誤:東西是錯誤的Directory dir = Directory("alex");
(刪除拷貝構造函數的使用)。使用由Directory("alex")
創建的臨時實例初始化dir
。
這是很容易改變:
int main()
{
Directory dir("alex"); // <-- fixed: direct construction
Directory dir2;
dir2 = dir;
cout<<"done"<<endl;
return 0;
}
編譯...
錯誤:東西是錯誤的Directory dir2;
。
A yepp。您定義了構造函數Directory(string name);
。這將禁止在此處需要的默認構造函數的自動創建。
我們要麼可以在默認的構造函數添加到class Directory
:
Directory() = default;
,或者我們可以改善現有的非默認的構造函數,以便它可以被使用的默認構造函數:
Directory(string name = string()): name(name) { }
整個來源:
#include <iostream>
#include <string>
using namespace std;
class Directory{
string name;
public:
Directory(string name = string()):name(name) {
}
~Directory() {
cout << "Deleting was called" <<endl;
}
Directory& operator=(Directory& other){
cout << "cp assigment" <<endl;
return *this;
}
Directory& operator=(Directory&& other){
cout << "move assigment" <<endl;
return *this;
}
};
int main() {
//Directory dir = Directory("alex");
Directory dir("alex");
Directory dir2;
dir2 = dir;
cout<<"done"<<endl;
// your code goes here
return 0;
}
現在,它編譯es和作品。
輸出:
cp assigment
done
Deleting was called
Deleting was called
你可以看到它住在ideone。
賦值是針對您的案例中的指針('Directory *')完成的。刪除'*'和'new',它會起作用。 – Scheff
你正在使用指針,你會如何期望副本被稱爲? – user0042
'dir = dir2;'調用內置的指針複製賦值運算符,而不是您的類複製賦值運算符。 – VTT