簡體   English   中英

C ++指針運行時錯誤-使用指針設置變量然后檢索

[英]C++ pointers runtime error - setting a variable with pointers then retrieving

我正在設置一個原型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;
}
...

Inventory.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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM