简体   繁体   中英

Class-in-class object constructor/initialization fails

I'm pretty new to C++ terminology so hopefully my title is not too off. But I'm 100% sure that someone will tell me ;)

I have this piece of code:

struct B {
  struct A {
    A() : a(0) { }
    A(int a) { this->a = a; }
    int a;
  }
    a0,    // OK
    a1(1); // NOT OK!

  B() : b(0) { }
  B(int b) { this->b = b; }
  int b;
}
  b0,    // OK
  b1(1); // OK

But gcc fails to compile and generates this output:

8:8: error: expected identifier before numeric constant
8:8: error: expected ‘,’ or ‘...’ before numeric constant
2:3: error: new types may not be defined in a return type
2:3: note: (perhaps a semicolon is missing after the definition of ‘B::A’)

If I remove 'a1(1)' object or change it to 'a1' then it compiles without problems. But then I can't make use of 'A(int a)' constructor. The similar? object 'b1' has no problems with its contructor. What's the explanation for this? Thanks :)

You are mismatching objects and instances. You cannot have a pre-constructed object (an instance of A) in the definition of class B, unless it is static const, but then you wouldn't still be able to initialize it in the class declaration.

You are not allowed to initialize a member variable within the class/struct defintion (exception: static const integral (eg int , short , bool ) members)

In the case of b0 and b1 , you are declaring (and initializing) two global variables, not member variables

a0 and a1 are members of the outer struct, and just like normal attributes, you cannot initalize them inline. You'll need to initialize a0 and a1 in your B constructor initalizer lists.

If you're asking for the correct syntax..,

struct B {
    struct A {
        int a;

        A()      : a(0) { }
        A(int a) : a(a) { }
    } a0, a1;

    int b;

    B()      : a0(), a1(1), b(0) { }
    B(int b) : a0(), a1(1), b(b) { }
} b0, b1(1);

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