C++基础复习提升-常用写法类初始化列表
参考C++那些事-光城大佬的网站
参考C++初始化列表,知道这些就够了
上一篇-C++基础复习提升-explicit那些事
下一篇-C++基础复习提升-assert那些事
初始化列表应用场景
- 如果没有定义任何构造函数,C++编译器会自动创建一个默认构造函数。
- 如果已经定义了一个构造函数,编译器不会自动创建默认构造函数,只能显示调用该构造函数
初始列表总结
- 因为初始化列表中无法直接初始化基类的数据成员,所以你需要在列表中指定基类的构造函数,如果不指定,编译器会调用基类的默认构造函数。
- 推荐使用初始化列表,它会比函数体内初始化派生类成员更快 , 这是因为在分配内存后,在函数体内又多进行了一次赋值操作。
- 初始化列表并不能指定初始化的顺序,正确的顺序是,首先初始化基类,其次根据派生类成员声明次序依次初始化。
// inline.h
#ifndef _A
#include <iostream>
class Base
{
public:
explicit Base(int x, int y, std::string n);
private:
const int a;
int &b;
std::string name;
};
class BaseChild : public Base
{
public:
explicit BaseChild(int x, int y, std::string n);
};
#endif
// main.cpp
#include <iostream>
#include "inline.h"
using namespace std;
// 作用域解析运算符+初始化列表
Base::Base(int x, int y, string n) : a(x), b(y), name(n)
{
cout << "x=" << x << "|y=" << y << "|n=" << n << endl;
}
BaseChild::BaseChild(int x, int y, string n) : Base(x, y, n)
{
cout << "cx=" << x << "|cy=" << y << "|cn=" << n << endl;
}
int main()
{
// 输出:
// x=1|y=2|n=sun
// x=3|y=5|n=jan
// cx=3|cy=5|cn=jan
Base b(1, 2, "sun");
BaseChild bc(3, 5, "jan");
return 0;
}