【问题标题】:Errors nesting vectors<> within vectors<>在向量<>中嵌套向量<>时出错
【发布时间】:2011-08-25 08:13:47
【问题描述】:

我在向量中嵌套向量时遇到问题,相当于 C 中的 2D 数组。我已经尝试了在众多网站上发布的代码,但无济于事。

class Board
{
    public:
        vector< vector<Cell> > boardVect; //Decalre the parent vector as a memebr of the Board class    

        Board()
        {
            boardVect(3, vector<Cell>(3)); //Populate the vector with 3 sets of cell vectors, which contain 3 cells each, effectivly creating a 3x3 grid. 

        }
};

当我尝试编译时,我收到此错误:

F:\main.cpp|52|error: no match for call to '(std::vector >) (int, std::vector)'

第 52 行是:boardVect(3, vector&lt;Cell&gt;(3));

是我在用 3 个向量类构造父向量时遇到错误吗?

【问题讨论】:

    标签: c++ class vector nested-class


    【解决方案1】:

    您需要使用初始化列表来调用类成员的构造函数,即:

    Board()
        :boardVect(3, vector<Cell>(3))
    {}
    

    一旦进入构造函数的主体,为时已​​晚,所有的成员都已经构造好了,只能调用非构造函数的成员函数。你当然可以这样做:

    Board()
    {
        boardVect = vector<vector<Cell> >(3, vector<Cell>(3));
    }
    

    但首选初始化列表。

    【讨论】:

    • 是的,这是我的问题,谢谢!我现在正在使用初始化列表;但我会记住用于创建对象的非构造函数。
    猜你喜欢
    • 2021-12-25
    • 2017-04-17
    • 2014-09-28
    • 2021-12-19
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多