【发布时间】:2013-05-25 11:31:52
【问题描述】:
能否请您指出正确的语法。这是到目前为止的代码
enum Color {WHITE, BLACK};
struct Square
{
Square(Color p_color): color_(p_color) {}
Color color_;
};
//instead of Square *, is there a clear way to express intention that function returns
//Square[][]
Square[][] initSquare(const int rows, const int cols)
{
Square board[rows][cols]; //Why does compiler complain that Square does not
//have a default constructor? I am just declaring an
//array of type Square
for(int row=0;row<rows;row++)
for(int col=0;col<cols;col++)
{
if(col%2 == 0)
board[row][col]= Square(WHITE);
else
board[row][col] = Square(BLACK);
}
return board;
}
【问题讨论】:
-
在 C++ 中,您不能拥有具有动态大小的数组,它们必须具有预定义的大小。要动态声明它们,请使用指针和“new”运算符。
-
@MatsPetersson 我不清楚如何声明一个二维对象数组,而不调用诸如 Square board[rows][cols]; 之类的构造函数;其他链接似乎对解决这个问题没有帮助
标签: c++