Initialization of data members
2024-10-12 11:06:18
In C++, class variables are initialized in the same order as they appear in the class declaration.
Consider the below code.
1 #include<iostream>
2
3 using namespace std;
4
5 class Test
6 {
7 private:
8 int y;
9 int x;
10 public:
11 Test() : x(10), y(x + 10)
12 {
13 }
14 void print();
15 };
16
17 void Test::print()
18 {
19 cout<<"x = "<<x<<" y = "<<y;
20 }
21
22 int main()
23 {
24 Test t;
25 t.print();
26 getchar();
27 return 0;
28 }
The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.
So one of the following two versions can be used to avoid the problem in above code.
1 // First: Change the order of declaration.
2 class Test
3 {
4 private:
5 int x;
6 int y;
7 public:
8 Test() : x(10), y(x + 10)
9 {
10 }
11 void print();
12 };
13
14 // Second: Change the order of initialization.
15 class Test
16 {
17 private:
18 int y;
19 int x;
20 public:
21 Test() : x(y-10), y(20)
22 {
23 }
24 void print();
25 };
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:http://www.cnblogs.com/iloveyouforever/
2013-11-26 10:23:29
最新文章
- Spring Boot构建RESTful API与单元测试
- vs2010 使用vs online账号 需要安装的插件
- Angularjs 中使用指令绑定点击事件
- Objective-C的内省(Introspection)小结
- Unity3D除了在编辑器里,怎么用代码给一个Texture类型的变量赋值
- Ext基础一(转载)
- crm采用soap删除记录
- JUnit4教程-高速入口
- Spark性能调优之代码方面的优化
- Cookie中的HttpOnly详解
- 图论算法-网络最大流【EK;Dinic】
- python条件控制
- Linux-高可用Keepalived概念篇
- django 加载css、js和图片记载不上
- python之路--FTP 上传视频示例
- 给大厨写的R数据分析代码
- shell脚本(一)
- day_5.27py
- iphone 恢复出厂设置方法
- BZOJ5099 POI2018Pionek