gpt4 book ai didi

c++ - 创建类的二维数组

转载 作者:太空狗 更新时间:2023-10-29 21:45:10 24 4
gpt4 key购买 nike

您好,如果有人可以建议如何正确执行此操作。基本上,我正在尝试创建一个名为 Board 的类变量,其中包含 ChessPiece 实例的二维数组。

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;

class ChessPiece
{
public:
char ToChar() { return '#'; };
};

class ChessBoard
{
int Size; //This means board is 8x8.
ChessPiece ** Board;

public:
ChessBoard();
int GetSize() { return Size; };

void PlotBoard();
};

ChessBoard::ChessBoard() {
Size = 8;
ChessPiece newBoard[Size][Size];
Board = newBoard; //Problem here!!! How do I make Board an 8x8 array of ChessPiece?
}

void ChessBoard::PlotBoard() {
int x, y;
for (x = 0; x < Size; x++) {
for (y = 0; y < Size; y++)
printf("%c", Board[x][y].ToChar());
}
}

int main()
{
// ChessBoard board;
// printf("%d", board.GetSize());
// board.PlotBoard();

ChessBoard * a = new ChessBoard();

return 0;
}

我在这里真的缺少非常基本的东西,但我似乎无法弄清楚。谢谢!

最佳答案

确实没有理由在您的场景中使用原始指针。我建议将棋盘保持为一维 std::vector,并在迭代棋盘时简单地使用行/列的乘法。

class ChessBoard
{
public:
ChessBoard(size_t row_count) : Size(row_count), Board(row_count * row_count)
{
}

void PlotBoard()
{
for(size_t row = 0; row < Size; ++row)
{
for(size_t col = 0; col < Size; ++col)
printf("%c", Board[(row * Size) + col].ToChar());
}
}
}

private:
size_t Size;
std::vector<ChessPiece> Board;
};

关于c++ - 创建类的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18216988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com