[英]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
整數(例如int
, short
, bool
)成員)
對於b0
和b1
,您聲明(並初始化)兩個全局變量,而不是成員變量
a0
和a1
是外部結構的成員,就像普通屬性一樣,您不能內聯初始化它們。 您需要在B
構造函數初始化列表中初始化a0
和a1
。
如果您要求正確的語法..,
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.