まず最初に、この数時間に受けたすべての支援に感謝します。私はこの問題に苦労してきました。生のポインタから一意のポインタに変換する方法で、多くのエラーが発生しました。しかし、このコミュニティの助けを借りて、私のプログラムが最終的にエラーなしでコンパイルされたことに感謝しています. しかし、私はまだそこにいないと思います。ゴールまであと1分という感じなので、解けるまで諦めません。プログラムが実行されるとすぐにクラッシュし、スタック オーバーフローが発生して例外がスローされます。コンストラクターのクラスメンバーとして一意のポインターを宣言および初期化する方法がまったく正しくないため、コンストラクターを呼び出した瞬間からクラッシュする必要があると思います。このエラーを修正するために何をすべきか教えてください。ありがとう。
これは私のメインの cpp ファイルです:
#include"ContactList.h"
#include<memory>
using namespace std;
int main()
{
//ContactList* cl1 = new ContactList();
unique_ptr<ContactList> cl1(new ContactList());
string name;
while(true)
{
cout << "Enter a name or q to quit: " << endl;
cin >> name;
if(name == "q")
break;
cl1->addToHead(name);
}
cl1->PrintList();
return 0;
}
ContactList.h
#pragma once
#include"Contact.h"
#include<memory>
using namespace std;
class ContactList
{
public:
ContactList();
void addToHead(const std::string&);
void PrintList();
private:
//Contact* head;
unique_ptr<Contact> head;
int size;
};
ContactList.cpp
#include"ContactList.h"
#include<memory>
using namespace std;
ContactList::ContactList(): head(new Contact()), size(0)
{
}
void ContactList::addToHead(const string& name)
{
//Contact* newOne = new Contact(name);
unique_ptr<Contact> newOne(new Contact(name));
if(head == 0)
{
head.swap(newOne);
//head = move(newOne);
}
else
{
newOne->next.swap(head);
head.swap(newOne);
//newOne->next = move(head);
//head = move(newOne);
}
size++;
}
void ContactList::PrintList()
{
//Contact* tp = head;
unique_ptr<Contact> tp(new Contact());
tp.swap(head);
//tp = move(head);
while(tp != 0)
{
cout << *tp << endl;
tp.swap(tp->next);
//tp = move(tp->next);
}
}
Contact.h
#pragma once
#include<iostream>
#include<string>
#include<memory>
class Contact
{
friend std::ostream& operator<<(std::ostream& os, const Contact& c);
friend class ContactList;
public:
Contact(std::string name = "none");
private:
std::string name;
//Contact* next;
std::unique_ptr<Contact> next;
};
Contact.cpp
#include"Contact.h"
using namespace std;
Contact::Contact(string n):name(n), next(new Contact())
{
}
ostream& operator<<(ostream& os, const Contact& c)
{
return os << "Name: " << c.name;
}
これは私が得るエラーです:
Unhandled exception at 0x77E3DEFE (ntdll.dll) in Practice.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x002B2F58).