C++ 引用的初始化列表有关顺序问题。

示例一:

#include <iostream>
using namespace std;

class cstu
{
public:
	int &a;
	int b;
	cstu():a(b) ,b(12)
	{
		
	} 
	void show()
	{
		cout << a << endl << b << endl;
	}
private:
	
protected:
	
};

int main()
{
	cstu stu;
	stu.show();
	return 0;
} 

结果

12

12

示例二:去掉示例一中的引用符号

#include <iostream>
using namespace std;

class cstu
{
public:
	int a;
	int b;
	cstu():a(b) ,b(12)
	{
		
	} 
	void show()
	{
		cout << a << endl << b << endl;
	}
private:
	
protected:
	
};

int main()
{
	cstu stu;
	stu.show();
	return 0;
} 

结果:

一个随机数

12

 

问题:

示例二是因为初始化顺序是按照成员变量声明顺序进行的,在初始化变量a时,变量b没有初始值,所以随机数。

那么为什么添加了引用之后,就会输出a为12了呢?????

我明白了,用变量b对引用a初始化是将a关联到b的空间上,那么此时a、b值相同,是一个随机值,然后对b初始化,使得a、b均为12。

赞自问自答