问题
I run across a weird concept named "member initializer".
Here says:
C++11 added member initializers, expressions to be applied to members at class scope if a constructor did not initialize the member itself.
What is its definition?
Are there some examples to illustrate its usage?
回答1:
It probably refers to in-class member initializers. This allows you to initialize non-static data members at the point of declaration:
struct Foo
{
explicit Foo(int i) : i(i) {} // x is initialized to 3.1416
int i = 42;
double x = 3.1416;
};
More on that in Bjarne Stroustrup's C++11 FAQ.
回答2:
You can now add initializers in the class which are shared for the constructors:
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
};
It avoids having to repeat initializers in the constructor which, for large classes, can be a real win.
回答3:
C++11 allows non-static member initialization like this:
class C
{
int a = 2; /* This was not possible in pre-C++11 */
int b;
public:
C(): b(5){}
};
回答4:
From here:-
Non-static Data Member Initializers are a rather straightforward new feature. In fact the GCC Bugzilla reveals novice C++ users often tried to use it in C++98, when the syntax was illegal! It must be said that the same feature is also available in Java, so adding it to C++ makes life easier for people using both languages.
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;
回答5:
Member initializers is referring to the extension of what initializers can be set up in the class definition. For example, you can use
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"
};
to have bar
initialized to hello
if the member initializer list doesn't give another value. Note that member initializers are not restricted to build-in types. You can also use uniform initialization syntax in the member initializer list.
来源:https://stackoverflow.com/questions/18811742/what-is-member-initializer-in-c11