クラスCのメンバー変数a
とb
の初期化の順序についてgccに警告する必要がありますか?基本的にオブジェクトbは初期化され、オブジェクトAの前にコンストラクタが呼び出されます。つまり、b
は初期化されていないa
を使用します。 GCCからgcc:コンストラクタの初期化順序に関する警告がありません
#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