对数据成员进行初始化
- 可通过数值对数据成员进行初始化;
- 可通过构造函数参数对数据成员进行初始化;
- 可通过成员之间相互初始化
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;
}