错误分配使用指向类的指针

时间:2014-04-26 23:32:50

标签: c++ class pointers

我一直在为练习编写粗略的基于文本的冒险,但我遇到了这个问题,我无法弄清楚如何修复崩溃。我担心这个问题有点高于我的技能水平,所以我会尝试在这里得到一个答案。

我会尝试发布相关内容。

class Location{
public:
Location *ConnectionNorth,
          *ConnectionSouth;
    void ConnectedNorth(Location room){ConnectionNorth = &room;}
    void ConnectedSouth(Location room){ConnectionSouth = &room;}
}
int main(){
  Location roomA;
  Location roomB
  Location *currentRoom;
  roomA.ConnectedNorth(roomB);//room B is connected to A to the North
  roomB.ConnectedSouth(roomA);//room A is connected to B to the South
  currentRoom = &roomA;
while(playing){
 //get input
    if(input == wants to go north)
      currentRoom = currentRoom->ConnectionNorth;
      //tell user they're in room B
    if(input == wants to go south)
      currentRoom = currentRoom->ConnectionSouth;
      //tell user they're in room A
}

令人讨厌的部分是我的代码在崩溃之前用于房间更改大约3次,我认为这是因为我对指针做错了,但我缺乏知识。

1 个答案:

答案 0 :(得分:0)

void ConnectedNorth(Location room){ConnectionNorth = &room;}

只要此函数返回,room就不复存在了。因此,您已将参数保存到已被销毁的Location。你可能意味着:

void ConnectedNorth(Location& room){ConnectionNorth = &room;}