What is “member initializer” in C++11?

こ雲淡風輕ζ 提交于 2019-12-01 15:18:09
juanchopanza

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.

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.

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){}

};

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;

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!