我需要知道爲什麼這個程序在我編譯時終止。我不明白終止的原因是什麼。 請告訴我他們的問題也是他們的解決方案。 謝謝。C++程序終止
#include<iostream.h>
class citizen{
private:
char* name;
char* nationality;
public:
citizen(){
name = "No name is given";
nationality = "No nationality is given\n";
}
citizen(char* name, char* nationality){
this->name = name;
this->nationality = nationality;
}
void display(){
cout << "Name: " << name << endl;
cout << "Nationality: " << nationality << endl;
}
~citizen(){
if(name){
cout << endl << "\nGoing to delete: "<< name << endl;
delete []name;
}
if(nationality){
delete []nationality;
cout << "Going to nationality: "<< nationality << endl;
}
}
citizen(const citizen &obj){
int size = sizeof(obj.name);
name = new char[size+1];
strcpy(name, obj.name);
int size2 = sizeof(obj.nationality);
nationality = new char[size2 + 1];
strcpy(nationality, obj.nationality);
cout << "\nI'm copy construcotr\n";
}
};
如果您使用的是C++,那麼使用'string'代替c-style字符串有什麼危害。 – Arpit
在你的析構函數中使用'delete []'會導致你在你的拷貝構造函數沒有創建你的對象的時候遇到很大的問題,就像在試圖刪除它之後嘗試輸出'nationality'一樣。 –
不不不不!現在停下來,忘記你學習過的關於C++的一切。停止使用'new []'和'delete []'。瞭解RAII,標準庫(尤其是容器和字符串)並閱讀[良好的C++書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 – rightfold