割り当て担当者に問題があります。赤い下線のエラーはありませんが、私はプログラムがmain.cppに中アクセス違反書き込み場所0x00000028
emp1 = emp2;
で壊れるコンパイルするとき、私は代入演算機能を追加するまで、すべてが働いていました。
何かアドバイスをいただければ幸いです。
編集:ちょうど全体の問題ではなく、問題に関連する特定のコードを表示する必要があると思った。ここで
は、私が書いたものだ:ListOfEmp.h
public:
ListOfEmp();
ListOfEmp(const ListOfEmp &);
~ListOfEmp();
const ListOfEmp& operator=(const ListOfEmp e);
};
ListOfEmp.cpp
ListOfEmp::ListOfEmp():head(NULL)
{
}
ListOfEmp::ListOfEmp(const ListOfEmp &e) {
*this = e;
}
ListOfEmp::~ListOfEmp()
{
clear();
}
const ListOfEmp& ListOfEmp::operator=(const ListOfEmp e){
if (this != &e) {
clear();
EmpNode* copy = NULL;
EmpNode* orig = e.head;
while (orig != NULL) {
if (head = NULL) {
head = copy = new EmpNode((orig->emp).name, (orig->emp).salary);
}
else {
copy->next = new EmpNode((orig->emp).name, (orig->emp).salary);
copy = copy->next;
}
orig = orig->next;
}
}
return *this;
}
void ListOfEmp::clear() {
EmpNode* temp = head;
while (temp != NULL) {
temp = temp->next;
delete head;
head = temp;
}
}
MAIN.CPP
int main() {
ListOfEmp emp1;
emp1.insertAtfront("John", 20000.00);
emp1.insertAtfront("Dave", 24500.50);
emp1.insertAtfront("Joshua", 33567.60);
emp1.deleteMostRecent();
emp1.getSalary("Dave");
cout << endl;
cout << emp1;
cout << endl;
ListOfEmp emp2;
emp2.insertAtfront("Julio", 54000.00);
emp2.insertAtfront("Mike", 12000.00);
emp2.getSalary("Mike");
cout << endl;
cout << emp2;
cout << endl;
emp1 = emp2;
cout << emp1;
cout << endl;
cout << emp2;
system("pause");
}
コピーコンストラクタの '* this = e;'は、風に対して100マイルのにおいをします。 – user0042
説明できますか?私はこれが私がコピーコンストラクタのために書いたはずのものだと思った。 – Kujinn
あなたの 'operator = 'がいかに良いかによって変わります。従来の知恵は、コピーコンストラクタに基づいて '= 'を使用して逆のやり方をすることです。それを読んで:[コピーとスワップのイディオムは何ですか?](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)重いですが、それは常に動作し、それは金の重さの価値がある。 – user4581301