必须用到初始化成员列表的四种情况:
- 初始化一个引用类型的成员变量
因为引用在使用的时候必须进行初始化操作
#include <iostream>
using namespace std;
class A
{
public:
A(int &v) : i(v), p(v), j(v) {
}
void print_val() {
cout << "hello:" << i << " " << j << endl;}
private:
const int i;
int p;
int &j;
};
int main(int argc ,char **argv)
{
int pp = 45;
A b(pp);
b.print_val();
}
- 初始化一个const修饰的成员变量
因为const修饰的成员变量就变成了常量,常量在使用的时候要进行初始化
const对象或引用只能初始化但是不能赋值。构造函数的函数体内只能做赋值而不是初始化,因此初始化const对象或引用的唯一机会是构造函数函数体之前的初始化列表中。
从无到有叫初始化,初始化(调用拷贝构造函数)创建了新对象;赋值(调用赋值操作符)没有创建新对象,而是对已有的对象赋值。
3) 调用一个基类的构造函数,而该函数带有非缺省的参数
#include <iostream>
using namespace std;
class Base
{
public:
Base(int a) : val(a) {
}
private:
int val;
};
class A : public Base
{
public:
A(int v) : p(v), Base(v) {
}
void print_val() {
cout << "hello:" << p << endl;}
private:
int p;
};
int main(int argc ,char **argv)
{
int pp = 45;
A b(pp);
b.print_val();
}
- 调用一个数据成员对象的构造函数,而该函数带有非缺省的参数
下面的例子讲的就是调用基类的构造函数,而该函数带有非缺省的参数
#include <iostream>
using namespace std;
class Base
{
public:
Base(const string &str = "", int i = 0) : Bstr(str), _i(i) // 使用const引用避免复制,
// 如果只使用const则无法使用字面常量"DerivedStr"为str赋值
{
cout << "Base Constructor" << " Bstr = " << Bstr << ", _i = " << _i << endl;
}
string Bstr;
int _i;
};
class Derived : public Base
{
public:
// 调用基类构造函数,而该函数带有非缺省的参数,要使用成员初始化列表
Derived() : Base("DerivedStr", 200) // 这个是正确的
{
//Base::Bstr = "DerivedStr"; // 基类构造函数再次之前调用,这里赋值没有用。
//Base::_i = 200;
cout << "Derived Constructor" << endl;
}
string Dstr;
};
int main()
{
Derived d;
return 0;
}