【发布时间】:2014-06-16 08:42:20
【问题描述】:
我一直在写一个粗略的基于文本的冒险练习,但我遇到了这个问题,我不知道如何解决崩溃问题。恐怕这个问题有点超出我的水平,所以我会在这里尝试得到答案。
我将尝试仅发布相关内容。
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 次房间更改,我认为这是因为我的指针做错了,但我缺乏相关知识。
【问题讨论】:
-
void ConnectedNorth(Location room)不正确 - 您想发送参考或直接向上的指针。您现在拥有的代码创建一个本地副本,分配指针,然后破坏本地副本,使指针无效。 -
这似乎更像是一个问题。
-
你没有初始化所有的指针。如果一半的指针未初始化,它最终崩溃也就不足为奇了。
-
+1 仍在进行文字冒险。