C++11--可以这么玩初始化列表吗?
2016-07-06 00:13
417 查看
我们知道C++11新增了初始化列表,在之前的博客中也有过介绍。
浅析C++中的初始化列表(区别赋值和初始化)
c++11特性之initializer_list
今天就讨论这么用初始化列表,不喜勿喷。
先写一个类:
使用这个类:
输出:
SimpleType::ctor, {1, 1, “string”}
来说说什么这么写有用:
1简洁
2你不会忘记初始成员变量
3当你有好几个构造函数的时候,这么写更有好处
对上面的类就行简单的修改:
对修改后的类进行使用:
使用:
输出:
使用:
输出:
副作用:
想要一个空的成员变量的时候,比如vector等等。
浅析C++中的初始化列表(区别赋值和初始化)
c++11特性之initializer_list
今天就讨论这么用初始化列表,不喜勿喷。
先写一个类:
class SimpleType { private: int a { 1 }; // << wow! int b { 1 }; // << wow2! string name { "string" }; // wow3! public: SimpleType() { cout << "SimpleType::ctor, {" << a << ", " << b << ", \"" << name << "\"}" << endl; } ~SimpleType() { cout << "SimpleType::destructor" << endl; } };
使用这个类:
SimpleType obj;
输出:
SimpleType::ctor, {1, 1, “string”}
来说说什么这么写有用:
1简洁
2你不会忘记初始成员变量
3当你有好几个构造函数的时候,这么写更有好处
对上面的类就行简单的修改:
class SimpleType { private: int a { 1 }; // << wow! int b { 1 }; // << wow2! string name { "string" }; // wow3! public: SimpleType() { /* old code... */ } SimpleType(int aa, int bb) : a(aa), b(bb) // << custom init! { std::cout << "SimpleType::ctor(aa, bb), {" << a << ", " << b << ", \"" << name << "\"}" << std::endl; } ~SimpleType() { cout << "SimpleType::destructor" << endl; } };
对修改后的类进行使用:
class AdvancedType { private: SimpleType simple; public: AdvancedType() { cout << "AdvancedType::ctor" << endl; } AdvancedType(int a) : simple(a, a) { cout << "AdvancedType::ctor(a)" << endl; } ~AdvancedType() { cout << "AdvancedType::destructor" << endl; } };
使用:
AdvancedType adv;
输出:
SimpleType::ctor, {1, 1, "string"} AdvancedType::ctor
使用:
AdvancedType advObj2(10);
输出:
SimpleType::ctor(aa, bb), {10, 10, "string"} AdvancedType::ctor(a)
副作用:
想要一个空的成员变量的时候,比如vector等等。
相关文章推荐
- C++中的三大缺省函数 之 《深拷贝与浅拷贝》
- C++对象模型学习——Data语意学
- C/C++ 实现QQ/微信刷消息
- c++ 生成pdf
- libharu(1):windows下编译方法
- C++ json string 发送之 base64
- C++缺省参数
- C++多态
- 一起talk C栗子吧(第一百七十二回:C语言实例--关闭终端中的回显功能三)
- C++派生访问控制说明符
- C语言字符串查找替换
- c++ 虚析构函数
- POJ 1330 Nearest Common Ancestors
- C++类中的static数据成员,static成员函数
- C++ typedef用法小结
- 动态规划--背包问题
- C++标准库和标准模板库
- 关于C语言给变量分配地址
- C++11中auto的使用
- C++11中auto的使用