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:
原文链接: https://www.cnblogs.com/TonyYPZhang/p/6537330.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/250682
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!