Initialization of data members
2013-11-26 10:24
190 查看
In C++, class variables are initialized in the same order as they appear in the class declaration.
Consider the below code.
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.
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
Consider the below code.
#include<iostream> using namespace std; class Test { private: int y; int x; public: Test() : x(10), y(x + 10) { } void print(); }; void Test::print() { cout<<"x = "<<x<<" y = "<<y; } int main() { Test t; t.print(); getchar(); return 0; }
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.
// First: Change the order of declaration. class Test { private: int x; int y; public: Test() : x(10), y(x + 10) { } void print(); }; // Second: Change the order of initialization. class Test { private: int y; int x; public: Test() : x(y-10), y(20) { } void print(); };
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
相关文章推荐
- 《转》如何成为一个牛逼的C/C++程序员?
- B-tree & B+tree & B*Tree 结构浅析——转
- android ListView中有按钮,无法获取焦点?android:descendantFocusability用法简析
- Eclipse中,常用的快捷键大全
- 时间测试函数
- Linux core dump的详细介绍及使用
- android ListView中有按钮,无法获取焦点?android:descendantFocusability用法简析
- 详解JMeter函数和变量
- zuccoj1450
- 读者写者问题——读者优先,写者优先,公平竞争 解决方法
- Linux内核源码分析方法
- python操作处理Excel文件(转)
- [Unity]让unity程序后台运行
- Renderer.materials
- java socket编程(网络编程)
- svn版本库创建
- 数据库查询,GROUP BY 的使用细节
- Cisco 端口策略检测
- sql多表行转列,级联行转列
- STL编程:C++的忠告!