Non-static data member initializers
非静的メンバ初期化子
Ideone.com - 6r5ja7 - Online C++0x Compiler & Debugging Tool
非静的メンバを構築時に初期化するには,コンストラクタにメンバ初期化子を記述する必要がありました(1).
int x; Foo() : x{1} // 1 ... {}
静的メンバの場合,実体の定義時に初期化子の指定ができます(2).
struct Foo { static int s; ... }; int Foo::s = 5; // 2
C++11では,静的メンバの初期化子に近い形で直感的に非静的メンバの初期化子を記述することができるようになりました(3).
int y = 2; // 3
新形式の初期化子は従来形式のコンストラクタに記述する初期化子でオーバーライドできます(4).
共に記述された場合はコンストラクタに記述した初期化子が優先されます.
int z = 3; // 4 Foo() : ... , z{4} // 4 {}
#include <iostream> struct Foo { static int s; int x; int y = 2; // 3 int z = 3; // 4 Foo() : x{1} // 1 , z{4} // 4 {} }; int Foo::s = 5; // 2 int main(int, char*[]) { Foo foo{}; std::cout << "x: " << foo.x << std::endl; std::cout << "y: " << foo.y << std::endl; std::cout << "z: " << foo.z << std::endl; std::cout << "s: " << Foo::s << std::endl; return 0; } || output: >| x: 1 y: 2 z: 4 s: 5 |< >|cpp| #include <iostream> struct Foo { static int s; int x; int y = 2; // 3 int z = 3; // 4 Foo() : x{1} // 1 , z{4} // 4 {} }; int Foo::s = 5; // 2 int main(int, char*[]) { Foo foo{}; std::cout << "x: " << foo.x << std::endl; std::cout << "y: " << foo.y << std::endl; std::cout << "z: " << foo.z << std::endl; std::cout << "s: " << Foo::s << std::endl; return 0; }
output:
x: 1 y: 2 z: 4 s: 5