0

我正在尝试在文本游戏练习中为 Room 创建一个框架。游戏的工作方式是房间是类,其中包含指向瓷砖指针数组的指针,每个瓷砖都有一个指向容器的指针,该容器代表瓷砖上的项目。

它的实现非常简单,并且编译得很好。Thing但是,当我尝试将对象“放置”到 a 上时,我遇到了一些问题Tile。这是通过多个传递函数传递指向 Thing 对象的指针来完成的。指针被传递给 Tile 的placeOnTile(Thing * i)函数,该函数将其传递给 Tile 的容器addItem(Thing* th)函数,该函数运行一个简单的检查以确保它适合容器(与 a 进行比较maxSize int),然后如果它适合则返回 true。

根据调试观察,指针(名为placer)在通道中没有改变(这很好)。但是,当它到达最终的透传函数(Container 的透传函数addItem(Thing* th))时,它会出现段错误并且不会继续运行程序。

下面列出了我能想到的相关代码示例。如果还有更多我应该包括的内容,请告诉我。

主要:

cout << "Bedroom Demo" << endl << endl;
    cout << "Creating bedroom obj...";
    Bedroom b1;  //this calls the constructor for Bedroom
    cout << "done." << endl << endl;

在 Bedroom.h 中:

Bedroom()   //constructor
{
    makeNineSquare(1); //this creates an arry of 9 Tiles, arranged in a 3x3 grid
    Thing* placer;  //this will point to objects that you'll create

    placer = new Bed("Your bed","This is your bed.",false,false,true,1);  //constructor
    ti[2]->placeOnTile(placer);  //!!!!This is where the error occurs!!!!

    placer = new Decor("North-facing Window","The window to the north looks out into barren space",false,false,true);
    ti[1]->placeOnTile(placer);

    placer = new Desk("Your desk","Your desk is wooden and antique.",0,0,1,5);
    ti[3]->placeOnTile(placer);

    delete placer;  //for memory leaks
}

在 Tile.h 中:

bool placeOnTile(Thing * i){return onTile->addItem(i);}

在Container.h(onTile是封装在Tile中的Container对象):

bool addItem(Thing* th);

在 Container.cpp 中:

bool Container::addItem(Thing* th)
{
     if (numItems < maxSize)
     {
         contents[++numItems] = th;
         return true;
     }
else return false;
}

正如我上面提到的,调试监视显示“通过”的每一步都可以正常工作,除了最后的传递(容器的传递)。我究竟做错了什么?

注意: ti 在 Bedroom 内声明。它是一个由 0 到 8 的 9 个图块组成的数组,它们构成了“房间”。该函数makeNineSquare只是一个在数组上实现二维链表​​的函数,创建指向相邻Tiles的NESW指针。我这样创建它的原因是为了便于使用数组放置在某些图块上(如提供的代码中所示),并便于使用指针的对象(例如播放器)轻松遍历网格。

这也允许全局通用移动命令(moveN只是curr = curr->getN代替计算来确定,例如,7 是否与 2 相邻)。

4

1 回答 1

0

根据您的代码,我不知道 numitems 是什么,但请检查 numitems++ 是否导致数组超出索引。

于 2013-06-22T22:02:49.333 回答