C++基础知识(初始化列表)

对数据成员进行初始化 

 ·可通过数值对数据成员进行初始化;

#include<iostream>
using namespace std;

class CStu
{
public:
	int a;
	float f;
	CStu() :a(1), f(12.21) //初始化格式
	{
		a = 13;  //13将12覆盖
		//cout << a << ' ' << f << endl;  //在构造函数中写输出语句,则在构造时就会输出
	}
	void Show()         //建议将输出语句独立出来
	{
		cout << a << ' ' << f << endl;
	}
};
int main()
{
	CStu stu;
	stu.Show();
	system("pause");
	return 0;
}

·可通过构造函数参数对数据成员进行初始化;

#include<iostream>
using namespace std;

class CStu
{
public:
	int a;
	float f;
	CStu(int d, float c) :a(d), f(c)    //原则:先声明谁就给谁先初始化,与初始化列表的顺序无关
	{
		//a = 13;  
		//cout << a << ' ' << f << endl;
	}
	void Show()
	{
		cout << a << ' ' << f << endl;
	}
};
int main()
{
	CStu stu(12,13.45f);//与构造函数中的参数类型位置保持一致
	stu.Show();
	system("pause");
	return 0;
}

·可通过成员之间相互初始化

#include<iostream>
using namespace std;

class CStu
{
public:
	int f;
	int a;
	CStu() :f(12), a(f)  //先对f初始化,再将f的值赋给a
	{
		//a = 13;  
		//cout << a << ' ' << f << endl;
	}
	void Show()
	{
		cout << a << ' ' << f << endl;
	}
};
int main()
{
	CStu stu;
	stu.Show();
	system("pause");
	return 0;
}

引用的初始化

#include<iostream>
using namespace std;

class CStu
{
public:
	int b;
	int& a;

	CStu() :a(b), b(12)
	{

	}
	void Show()
	{
		cout << a << ' ' << b << endl;
	}
};

int main()
{
	CStu stu;
	stu.Show();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_37753215/article/details/81835343