0

你能指点我正确的语法吗?这是到目前为止的代码

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;
}
4

1 回答 1

2
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

这会调用默认构造函数(即Square::Square())。你有一个带参数的构造函数。如果用户重载了构造函数,编译器不提供默认构造函数。所以编译器抱怨它。

其次,你不能board从函数中返回。board是一个块范围的变量,它的生命周期在函数返回后立即结束。您应该改为使用动态分配。

编辑:如果可能的话,避免动态分配。使用std::vector可以更好地简化任务。std::vector如果您不了解STL 容器,请在 Google上搜索。

#include <vector>

using namespace std; 

enum Color {WHITE, BLACK};

struct Square
{
  Color color_;
};

typedef vector<vector<Square> > chessBoard;

chessBoard initSquare(int rows, int cols)
{
    chessBoard board;

    for (int i=0; i<rows; ++i)
    {
        vector<Square> vSqr(cols); // You can pass the argument to the constructor
                                   // giving the second parameter here. But I
                                   // changed your interface a bit.

        for (int j=0; j<cols; ++j)
        {
            vSqr[j].color_ = (j%2 == 0) ? WHITE : BLACK;
        }
        board.push_back(vSqr);
    }

    return board;
}

int main()
{
    chessBoard board = initSquare(8,8);
    return 0;
}
于 2013-05-25T11:39:20.763 回答