1

我正在建立一个原型 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;
}
...

有任何想法吗?谢谢

4

1 回答 1

1

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

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;
}
于 2013-11-09T18:33:44.300 回答