简体   繁体   中英

Initialize std::array of classes in a class constructor

I'm trying to initialize a std::array of objects within the constructor of another class. It seems like aggregate initialization should work here, but I can't figure out the appropriate syntax. How do I go about doing this?

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

You just need an extra pair of braces:

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

Or you can replace parentheses with braces:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM