繁体   English   中英

类中的对象构造函数/初始化失败

[英]Class-in-class object constructor/initialization fails

我是C ++术语的新手,所以希望我的职称不太高。 但是我100%肯定有人会告诉我;)

我有这段代码:

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

但是gcc无法编译并生成以下输出:

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’)

如果删除“ a1(1)”对象或将其更改为“ a1”,则它可以毫无问题地进行编译。 但是后来我不能使用'A(int a)'构造函数。 相似吗? 对象“ b1”的构造函数没有问题。 这有什么解释? 谢谢 :)

您不匹配对象和实例。 除非它是静态const,否则在类B的定义中不能有一个预先构造的对象(A的实例),但是您仍然不能在类声明中对其进行初始化。

不允许在类/结构定义内初始化成员变量(例外: static const整数(例如intshortbool )成员)

对于b0b1 ,您声明(并初始化)两个全局变量,而不是成员变量

a0a1是外部结构的成员,就像普通属性一样,您不能内联初始化它们。 您需要在B构造函数初始化列表中初始化a0a1

如果您要求正确的语法..,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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