它可能指的是类内成员初始化器。这允许您在声明点初始化非静态数据成员:
struct Foo
{
explicit Foo(int i) : i(i) {} // x is initialized to 3.1416
int i = 42;
double x = 3.1416;
};
有关更多信息,请参阅Bjarne Stroustrup的C++11 FAQ。
class A
{
int i = 42;
int j = 1764;
public:
A() {} // i will be 42, j will be 1764
A( int i ) : i(i) {} // j will be 1764
};
使用初始化列表可以避免在构造函数中重复设置初始值,对于大型类来说,这是一个真正的优势。
C++11允许像这样进行非静态成员初始化:
class C
{
int a = 2; /* This was not possible in pre-C++11 */
int b;
public:
C(): b(5){}
};
private:
中定义int a = 2; int b;
,而不是在public:
中。 - BlackMamba成员初始化器是指扩展了类定义中可以设置的初始化器。例如,您可以使用
struct foo
{
std::string bar = "hello";
std::string baz{"world"};
foo() {} // sets bar to "hello" and baz to "world"
foo(std::string const& b): bar(b) {} // sets bar to b and baz to "world"
};
如果成员初始化列表没有提供另一个值,那么要将bar
初始化为hello
。请注意,成员初始化器不仅限于内置类型。您还可以在成员初始化列表中使用统一初始化语法。
从这里开始:
非静态数据成员初始化器是一个相当简单的新特性。事实上,GCC Bugzilla显示,初学者C++用户常常尝试在C++98中使用它,当时该语法是非法的!必须说,同样的特性也在Java中可用,因此将其添加到C++中使得同时使用这两种语言的人们更加容易。
struct A
{
int m;
A() : m(7) { }
};
struct B
{
int m = 7; // non-static data member initializer
};
thus the code:
A a;
B b;
std::cout << a.m << '\n';
std::cout << b.m << std::endl;