Search code examples
c++c++11initializer-listaggregate-initialization

c++11 initializer_list doesn't work for literal constant value of embedded object?


I've got a simple program in c++11:

struct A{
    int i;
    struct B{
        int i;
        int j;
    };
} a = {2, {3, 4}};

g++-7 compiles and gives error:

error: too many initializers for 'A'
 }a={2,{3,4}};
            ^

I just wonder how can I declare an object of A using literal constants, how to fix it?

Thanks a lot.


Solution

  • Since your type A only contains a single data member (of type int), you can have at most one element in your initializer:

    struct A{
        int i;
        struct B{
            int i;
            int j;
        };
    } a = {2};   // OK, a.i == 2
    

    (The fact that A also contains a type member (A::B) is immaterial to the creation of objects of type A.)