创建具有 new in 函数和"this is nullptr"异常的对象

Creating objects with new in function and "this is nullptr" exception

本文关键字:is this nullptr 异常 对象 new in 函数 创建      更新时间:2023-10-16

我一直在尝试创建一个模板类(称为List(,用于存储不同类型的对象。我创建了基类,就像我的程序和Human类中的基类一样。Base可以创建新的Human,并可以访问它们,它有一个指向List*first_h的(私有(指针(在每个列表中存储Human*me、List*next和List*first_h(列表中的first_h((。问题是,当我向我的基地添加超过1个人类时,我无法正确显示它们。我认为这是因为在Base方法中创建了新的Human(void Base::create_Human(字符串名称((,但我所做的一切都没有成功。这里有我的课程:

class Human
{
private:
string name;
public:
Human(string name) { this->name = name; }
void display() { cout << "My name: " << name << endl; }
};
template <class T>
class List
{
private:
T* me;
List <T>* next;
List <T>* first;
public:
void set_me(T* me) { this->me = me; }
T* get_me() { return this->me; }
void set_next(List* next) { this->next = next; }
List <T>* get_next() { return this->next; }
void set_first(List* first) { this->first = first; }
List <T>* get_first() { return this->first; }
void add(T*& created);
void display();
};
class Base
{
private:
List <Human>* first_h;
public:
void set_first_h(List <Human>*& first) { this->first_h = first; }
List <Human>* get_first_h() { return this->first_h; }
void create_human(string name)
{
Human* created = new Human(name);
this->first_h->add(created);
}
};

和方法:

template <class T>
void List<T>::add(T*& created)
{
List <T>* temp = this->get_first();
List <T>* new_list;
if ((this->get_me()) == nullptr)
{
this->set_next(nullptr);
this->set_me(created);
this->set_first(this);
}
else
{
new_list = new List <T>;
temp = this->get_first();
while (temp != nullptr)
{
temp = temp->get_next();
}
new_list->set_next(nullptr);
new_list->set_first(this->get_first());
temp->set_next(new_list);
}
}
template <class T>
void List<T>::display()
{   
List <T>* temp_list = this;
T* temp;
if (temp_list == nullptr)
{
std::cout << "There is nothing!" << endl;
}
while (temp_list != nullptr)
{   
temp = temp_list->get_me();
temp->display();
temp_list = temp_list->get_next();
}
std::cout << "End!" << endl;
}

以及我的主要功能:

int main()
{   
Base Main;
List <Human>* first_h = new List <Human>();
Main.set_first_h(first_h);
Main.create_human("Jane");
Main.create_human("John");
Main.create_human("Mary");
Main.get_first_h()->display();
system("pause");
return 0;
}

对不起我的英语,提前谢谢你!

编辑:我发现了问题所在:附加功能:

new_list->set_next(nullptr);
new_list->set_me(created);
new_list->set_first(this->get_first());
temp->set_next(new_list);

我忘了:

new_list->set_me(created);
  • 添加函数中的错误,正如您所写的那样

您的循环

while (temp != nullptr)
{
temp = temp->get_next();
}

运行直到温度为nullptr,然后执行

temp->set_next(new_list);

因此,如您所见,在set_next()内部,this指针是nullptr

请学习如何使用调试器并查看调用堆栈。

相关文章: