首页 > 编程语言 > 详细

[C++] in-class initializer

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!