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

最新文章

  1. Spring Boot构建RESTful API与单元测试
  2. vs2010 使用vs online账号 需要安装的插件
  3. Angularjs 中使用指令绑定点击事件
  4. Objective-C的内省(Introspection)小结
  5. Unity3D除了在编辑器里,怎么用代码给一个Texture类型的变量赋值
  6. Ext基础一(转载)
  7. crm采用soap删除记录
  8. JUnit4教程-高速入口
  9. Spark性能调优之代码方面的优化
  10. Cookie中的HttpOnly详解
  11. 图论算法-网络最大流【EK;Dinic】
  12. python条件控制
  13. Linux-高可用Keepalived概念篇
  14. django 加载css、js和图片记载不上
  15. python之路--FTP 上传视频示例
  16. 给大厨写的R数据分析代码
  17. shell脚本(一)
  18. day_5.27py
  19. iphone 恢复出厂设置方法
  20. BZOJ5099 POI2018Pionek

热门文章

  1. 添加su权限
  2. 大爽Python入门教程 2-1 认识容器
  3. 使用 @Transactional 时常犯的N种错误
  4. Go iota 原理和源码剖析
  5. cmd命令配置MySQL
  6. [loj3528]位移寄存器
  7. myeclipse maven web打包
  8. html+css第九篇
  9. 什么是JIT?
  10. Feed系统设计分析(类似微博的用户动态分享问题)