geeksforgeeks 025-数据成员的初始化

类成员的初始化顺序是按照类声明中出现的顺序排列的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>

using namespace std;

class Test {
private:
int y;
int x;
public:
Test() : x(10), y(x + 10) {}
void ();
};

void Test::print()
{
cout<<"x = "<<x<<" y = "<<y;
}

int main()
{
Test t;
t.print();
getchar();
return 0;
}

以上程序x值正确,y值错误,因为y在x之前初始化

以下两种方法可以解决问题

1
2
3
4
5
6
7
8
9

class Test {
private:
int x;
int y;
public:
Test() : x(10), y(x + 10) {}
void ();
};

1
2
3
4
5
6
7
8
9
// Second: Change the order of initialization.
class Test {
private:
int y;
int x;
public:
Test() : x(y-10), y(20) {}
void ();
};