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

对数据成员进行初始化 

  1. 可通过数值对数据成员进行初始化;
  2. 可通过构造函数参数对数据成员进行初始化;
  3. 可通过成员之间相互初始化

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

#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;
}

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

#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;
}

3 通过成员之间相互初始化

#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;
	const int e;
 
	CStu() :a(b), b(12), e(123)
	{
 
	}
	void Show()
	{
		cout << a << ' ' << b << ' ' << e << endl;
	}
};
 
int main()
{
	CStu stu;
	stu.Show();
	system("pause");
	return 0;
}

构造函数带参数

#include<iostream>
using namespace std;
 
class CStu
{
public:
	int b;
	int& a;
	const int e;
 
	CStu(int& c) :a(c), b(c), e(c)
	{
 
	}
	void Show()
	{
		cout << a << ' ' << b << ' ' << e << endl;
	}
};
 
int main()
{
	int d = 13;
	CStu stu(d);
	stu.Show();
	system("pause");
	return 0;
}

多个构造函数,初始化列表绑定所在的构造函数

#include<iostream>
using namespace std;
 
class CStu
{
public:
	int b;
	int& a;
	const int e;
 
	CStu(int& c) :a(c), b(c), e(c)          //构造函数1
	{
 
	}
 
	CStu(int& c, int m) :a(c), b(m), e(c) //构造函数2
	{
 
	}
 
	void Show()
	{
		cout << a << ' ' << b << ' ' << e << endl;
	}
};
 
int main()
{
	int d = 13;
	CStu stu1(d);
	CStu stu2(d, 1234);
	stu1.Show();
	stu2.Show();
	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值