您的位置:首页 > 其它

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.

#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: