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;
}
...
演员.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;
}
相关文章:
- 指针变量在 cout 函数中不起作用
- 如何将指针变量作为引用参数传递?
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 我试图了解在异或操作后指针变量正在更改
- 调用带有指针对象错误的指针变量
- 如何在 cuda 中将结构的指针变量从主机复制到设备
- 非指针变量和类成员上的新放置
- 线路抑制状态错误 C4703 可能未初始化的局部指针变量"back"已使用
- 全局外部指针变量在 DLL 中不可见
- 如何访问在 c++ 中在类内声明的结构类型指针变量?
- C++ 中指针变量的内存释放
- 使用指针变量打印特定的数组变量
- 如何使用构造函数初始化内存地址(指针变量)?
- 如何释放为指针变量本身提供的内存?
- 如果地址已知,如何获取指针变量的名称
- 如何处理参数中的基类和指针变量
- 指针变量 在数组中定位零
- 隐式指针变量,在自动定义中具有另一个指针变量
- 为什么可以将Char指针变量初始化为字符串,而INT指针变量不能初始化到整数数组
- 错误 C4703 可能未初始化的局部指针变量'y'使用