【问题标题】:Constructor for a 2d container array of structs结构的二维容器数组的构造函数
【发布时间】:2015-04-19 09:46:21
【问题描述】:

所以这是我的代码,我的错误是 error C2512: 'std::array<std::array<SudokuGrid::Cell,9>,9>' : no appropriate default constructor 我以为我提供了我的公共定义,但我一定遗漏了一些东西。我试图整合this问题的答案,但我无法得到正确的方法

class SudokuGrid
{
private:
    struct Cell{
        int value; 
        bitset<9> pencils; 
        bool isSolved; 
        Cell(int i, bitset<9> p, bool s):
            value{ i = 0 },
            pencils{ p.reset() },
            isSolved{ s = false }{}
    };
    array < array < Cell, 9>, 9 > _grid;

public:
    SudokuGrid(string s) :_grid{}
    {
        for (int i = 0; i < 9; i++)
            for (int j = 0; j < 9; j++)
            {
                bitset<9> p;
                p.reset();
                _grid[i][j] = Cell(0, p, false);
            }   
    }
};

【问题讨论】:

  • 表达式*new Cell(0, p, false); 造成内存泄漏,你分配内存并取消引用返回的指针,然后扔掉指针。相反,例如_grid[i][j] = Cell(...);.
  • 另外,在发布有关构建错误的问题时,请在问题中包含完整且未经编辑的构建日志,并在显示的代码中标出错误的位置。请编辑您的问题以包含该信息。
  • 但是,想想std::array很像一个普通的数组,所以数组中的对象会在创建数组的时候创建,所以你需要一个default 构造函数。如果你不做任何特殊的数组构造。

标签: c++ arrays constructor containers


【解决方案1】:

std::arraydefault constructs它所包含的元素的默认构造函数。所以SudokuGrid::Cell必须有一个默认构造函数:

Cell():
    value(0),
    pencils(),
    isSolved(false){}

完整代码见:http://goo.gl/CdpCH6

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2015-02-21
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多