gpt4 book ai didi

C++ 指针运行时错误 - 使用指针设置变量然后检索

转载 作者:太空宇宙 更新时间:2023-11-04 11:45:51 25 4
gpt4 key购买 nike

我正在设置原型(prototype) C++ 控制台应用程序。该程序包含一些虚拟类和指针等。当程序到达主函数中的以下代码行时,它会崩溃。我相信这与访问该指针处的内存有关。

主要()

...
Player _player(); //new player object created
Actor *player = &_player; //pointer to player created

...
//note player and get_inventory() are/return a pointer
{
Inventory* a = player->get_Inventory();
a->set_testMe("testedMe");
string result = a->get_testMe();
cout << result << endl;
}

{
Inventory* a = player->get_Inventory();
string result = a->get_testMe(); //This causes error
cout << result << endl;
}
...

Actor.cpp//get_Inventory()

...
Inventory* Actor::get_Inventory()
{
Inventory mInventory = this->actorInventory;
Inventory * pInventory = &mInventory;
return pInventory;
}
...

库存.cpp

...
Inventory::Inventory()
{
this->testMe = "initial test";
}

void Inventory::set_testMe(string input)
{
this->testMe = input;
}
string Inventory::get_testMe()
{
return this->testMe;
}
...

有什么想法吗?谢谢

最佳答案

返回一个指向局部变量的指针:

Inventory* Actor::get_Inventory()
{
Inventory mInventory = this->actorInventory;
Inventory * pInventory = &mInventory;
return pInventory;
}

第一个语句将 this->actorInventory 复制到局部变量中(如 get_Inventory 方法的局部变量),然后返回指向该局部变量的指针。一旦您从 get_Inventory() 返回,该变量就会超出范围并且不再存在。

您可能想尝试直接返回指向 this->actorInventory 的指针:

Inventory *Actor::get_Inventory()
{
return &actorInventory;
}

或者,如果您不希望调用者修改 actorInventory,则返回一个 const 限定指针:

const Inventory *Actor::get_Inventory() const
{
return &actorInventory;
}

关于C++ 指针运行时错误 - 使用指针设置变量然后检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19880161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com