【问题标题】:Initialize std::array of classes in a class constructor在类构造函数中初始化类的 std::array
【发布时间】:2016-02-16 08:10:24
【问题描述】:

我正在尝试在另一个类的构造函数中初始化一个 std::array 对象。似乎聚合初始化应该在这里工作,但我想不出合适的语法。我该怎么做?

class A {
        const int a;
public:
        A(int an_int) : a(an_int) {}
};

class B {
        std::array<A,3> stuff;
public:
        B() :
        stuff({1,2,3}) // << How do I do this?
        {}
};

int main() {
        B b;
        return 0;
}

【问题讨论】:

    标签: c++ c++11 initializer-list stdarray


    【解决方案1】:

    你只需要一对额外的牙套:

    B() : stuff({{1,2,3}}) {}
                ^       ^
    

    或者你可以用大括号代替括号:

    B() : stuff {{1,2,3}} {}
                ^       ^
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-21
      • 2015-09-04
      • 2022-01-22
      • 2016-12-29
      • 2014-02-27
      • 2016-05-03
      • 1970-01-01
      • 2015-12-29
      相关资源
      最近更新 更多