1

这段代码在 VS2010 中运行良好,但现在我正尝试使用 xcode 4.6 将它移植到我的 mac,它在运行时给了我一些糟糕的访问错误。基本上我有一个包含二维图块数组的板类,当我创建板时,我可以访问图块函数,但是当我稍后运行我的绘制函数时,它给了我不好的访问权限。这是我的董事会课程的示例。

板子.h

#include "Tile.h"
class Board
{
private:
    //This is the GameBoard of a 2D array of Tiles
    Tile *** GameBoard;
    void CreateBoard(const int size);
void FillValues();
    ...
public:
Board(int size);
void DrawBoard();
    ...
}

板子.cpp

Board::Board(const int size)
{
won=false;
lost=false;
BoardSize =size;
GameBoard = new Tile**[size];
CreateBoard(size);
}

void Board::CreateBoard(const int size)
{
    ...
    FillValues()
}

void Board::FillValues()
{
    for(int x=1;x<BoardSize+1;x++)
    {
        for(int y =1;y<BoardSize+1;y++)
        {
            if (GameBoard[x][y]->Type()=="NumberTile")
            {
                                int neighbors = CountNeighbours(x,y);
                GameBoard[x][y]->SetValue(neighbors);
                                //This works
            }
        }
    }
}

void Board::DrawBoard()
{
for(int i=0;i<=BoardSize+1;i++)
{
    for (int j=0;j<=BoardSize+1;j++)
    {
        if (GameBoard[i][j]->Type() != "BorderTile") {
            GameBoard[i][j]->Draw();
            //This does not work, i get the error when it tries to use ->Type()
        }
    }
}
}

...

我这样调用函数

GI = new Board(SCREEN_SIZE);
GI->DrawBoard();
4

1 回答 1

3
GameBoard = new Tile**[size];

这只是创建一个数组Tile**。您还没有任何实际Tile的 s 甚至Tile*s ,以后,当您尝试使用 访问数组的元素时GameBoard[x][y]->,您会遇到未定义的行为。

正如你所拥有的,你需要这样做:

GameBoard = new Tile**[size];      // Allocate an array of Tile**
for (int i = 0; i < size; i++) {
  GameBoard[i] = new Tile*[size];  // Allocate an array of Tile*
  for (int j = 0; i < size; j++) {
     GameBoard[i][j] = new Tile(); // Allocate an array of Tile
  }
}

然而,这很糟糕。这是三个动态分配,您必须记住最后整理(并正确整理)。

一种更简单的方法是只拥有一个二维瓷砖数组:

Tile GameBoard[CONSTEXPR_SIZE][CONSTEXPR_SIZE];

或者更好的是,使用std::array容器:

std::array<std::array<Tile, CONSTEXPR_SIZE>, CONSTEXPR_SIZE> GameBoard;

在这里,给定的大小必须是一个常量表达式。如果需要动态调整大小,请改用 a std::vector


在下面的评论中,您说数组的大小实际上是BoardSize+1. 尽管如此,您在外部和内部循环中都迭代了太多元素for

for(int i=0;i<=BoardSize+1;i++)

这应该是:

for(int i=0; i<BoardSize+1; i++)

同样在下面的评论中,您说Type返回 a char*。这意味着您不能像这样进行字符串比较:

GameBoard[i][j]->Type() != "BorderTile"

这只是执行指针比较,因为左操作数是 achar*而右操作数可以转换为const char*。它比较字符串本身。相反,你想要:

GameBoard[i][j]->Type() != std::string("BorderTile")

这将强制std::string使用比较。

于 2013-03-26T19:44:01.047 回答