24 October 2022

C++ 核心指南目录

“Use inheriting constructors to import constructors into a derived class that does not need further explicit initialization”

理由

如果在继承类中需要用到基类的构造函数,重新实现这些构造函数会比较繁琐、容易出错。

例子

std::vector 有一堆诡异的构造函数,所以,如果我要继承一个自己的向量类,我不需要重新实现这些构造函数。

class Rec {
    // ... data and lots of nice constructors ...
};

class Oper : public Rec {
    using Rec::Rec;
    // ... no data members ...
    // ... lots of nice utility functions ...
};

坏例子

struct Rec2 : public Rec {
    int x;
    using Rec::Rec;
};

Rec2 r {"foo", 7};
int val = r.x;   // uninitialized

强化

  • 确保继承类中的每个成员都初始化过。