我需要为类中的矩阵指定一个大小,但是使用 const int size
编译器会报错。有没有优雅的方式满足我的需求?
header.h
class ChessBoard {
int matrix[<size>][<size>];
public:
ChessBoard(int s): <size>(s) {}
};
main.cpp
#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;
}
最佳答案
在编译时不知道大小的情况下,你不能像这样创建数组。使用指针和 new 创建数组。使用这个数组的 child 将与使用 [][] 相同。唯一的区别是,您需要删除分配的数组,第一个将“自动”删除。
int ** matrix = new int*[s];
for (int i = 0; i < s; i++)
{
matrix[i] = new int[s];
}
最后从内存中删除[]
数组
for (int i = 0; i < s; i++)
{
delete[] matrix[i];
}
delete[] matrix;
关于c++ - 如何给类中的方阵指定大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16758652/