gcc 是否应该警告成员变量a
和b
C 类中的初始化顺序?基本上,对象 b 已初始化,并且在对象 A 之前调用它的构造函数。这意味着b
使用未初始化的a
.
#include <iostream>
using namespace std;
class A
{
private:
int x;
public:
A() : x(10) { cout << __func__ << endl; }
friend class B;
};
class B
{
public:
B(const A& a) { cout << "B: a.x = " << a.x << endl; }
};
class C
{
private:
//Note that because b is declared before a it is initialized before a
//which means b's constructor is executed before a.
B b;
A a;
public:
C() : b(a) { cout << __func__ << endl; }
};
int main(int argc, char* argv[])
{
C c;
}
来自 gcc 的输出:
$ g++ -Wall -c ConsInit.cpp
$