码迷,mamicode.com
首页 > 编程语言 > 详细

[C++] in-class initializer

时间:2017-03-12 13:28:43      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:fast   ide   com   cto   log   ict   into   rri   init   

C++11 introduced serveral contructor-related enhancements including:

  • Class member initializers
  • Delegating controctors

This article discusses about Class member initializers only.

 

Class member initializers are also called in-class initializers. C++11 follows other programming language that let you initializer a class member directly during its declaration:

Class M { // C++11
    int j = 5;    // in-class initializer
    bool flag(false);    // another in-class initializer
public:
    M();
};

M m1;    // m1.j = 5, m1.flag = false

The complier transforms every member initializers(such as int j = 5) into a controctor‘s member initializer. Therefore, the declaration of class M above is semantically equalment to the following C++03 class definition:

class M2{
    int j;
    bool flag;
public:
    M2(): j(5), flag(false) {}
}

If the constructor includes an explict member initializer for a member that also has an in-class initializer, the controctor‘s member intializer will override the in-class initializer.

class M2{
    int j = 7;    // in-class initializer
public:
    M2();    // j = 7
    M2(int i): j(i) {}    // overrides j‘s in-class intializer
};
M2 m2;     // j = 7
M2 m3(5);    // j = 5

 

Reference:

C++11 Tutorial: New Constructor Features that Make Object Initialization Faster and Smoother, smartbear.com

 

[C++] in-class initializer

标签:fast   ide   com   cto   log   ict   into   rri   init   

原文地址:http://www.cnblogs.com/TonyYPZhang/p/6537330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!