必须用到初始化成员列表的四种情况

来源:互联网 发布:什么直播软件有黄播 编辑:程序博客网 时间:2024/05/01 20:25

必须用到初始化成员列表的四种情况:

1) 初始化一个reference成员
2) 初始化一个const成员
3) 调用一个基类的构造函数,而该函数有一组参数
4) 调用一个数据成员对象的构造函数,而该函数有一组参数

摘自《C++对象模型》

下面的例子讲的就是调用基类的构造函数,而该函数有一组参数


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