2
gcc应该警告C类中成员变量a
和b
的初始化顺序吗?基本上,对象b被初始化,它的构造函数在对象A之前调用。这意味着b
使用未初始化的a
。从GCCgcc:对构造函数初始化的顺序没有警告
#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;
}
输出:
$ g++ -Wall -c ConsInit.cpp
$
什么是ouptput? –
你可以告诉它警告你。该标志是-Wreorder,它是用-Wall打开的。 –
你应该确保你用'-Wall -Werror -Wextra -pedantic-errors'进行编译。代码不会编译因为gcc会警告你你正在使用未初始化的 – inf