如何声明二维对象数组并从函数返回它

时间:2013-05-25 11:31:53

标签: c++

请指点我正确的语法。这是迄今为止的代码

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

1 个答案:

答案 0 :(得分: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())。你有一个构造函数参与。如果用户重载了构造函数,则编译器不提供默认构造函数。所以编译器抱怨它。

其次,您无法从函数返回boardboard是一个块范围变量,它的生命周期在函数返回后立即结束。你应该去做动态分配。

编辑: 如果可能,请避免动态分配。使用std::vector可以更好地简化任务。关于STL容器std::vector的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;
}