0

我需要给类内的矩阵一个大小,但是const int size编译器会抱怨。有一种优雅的方式可以满足我的需求吗?

头文件.h

class ChessBoard {
    int matrix[<size>][<size>];
public:
    ChessBoard(int s): <size>(s) {}
};

主文件

#include "header.h"
#include <iostream>
int main() {
    std::cout << "Enter the size of the chessboard: ";
    int n;
    std::cin >> n;

    ChessBoard cb(n);

    return 0;
}
4

2 回答 2

2

你不能像这样创建数组,不知道编译时的大小。使用指针和 new 创建数组。使用这个数组的孩子将与使用 [][] 相同。唯一的区别是,您需要删除分配的数组,第一个将被“自动”删除。

int ** matrix = new int*[s];
for (int i = 0; i < s; i++) 
{
   matrix[i] = new int[s];
}

最后delete[]是内存中的数组

for (int i = 0; i < s; i++) 
{
  delete[] matrix[i];
}
delete[] matrix;
于 2013-05-26T11:15:54.373 回答
2

为了实例化一个固定大小的矩阵,维度需要是编译时间常数。在您的情况下,大小是在运行时确定的。我建议使用std::vector<int>, 并在必要时提供双索引访问。2D 结构只会增加不必要的复杂性:

class ChessBoard 
{
  std::vector<int> matrix;
public:
  int& operator()(size_t row, size_t column) { /* get element from matrix*/ }
  constint& operator()(size_t row, size_t column) const { /* get element from matrix*/ }
  ChessBoard(int s): matrix(s) {}
};
于 2013-05-26T11:19:42.570 回答