【问题标题】:How to declare two dimensional array of objects and return it from a function如何声明对象的二维数组并从函数中返回它
【发布时间】: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++


【解决方案1】:
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 如果你不知道的话。

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

【讨论】:

  • 我如何声明一个 Square 对象的二维数组,它实际上调用了构造函数?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-19
  • 2012-01-26
  • 2011-07-09
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
相关资源
最近更新 更多