使用派生的[C++]生成的参数初始化基类

Initializing base class with parameters generated by derived [C++]

本文关键字:参数 初始化 基类 C++ 派生      更新时间:2023-10-16

我有一种情况,我有一些基类base,我从这个类派生DerivedA和DerivedB。让我们假设Base的c'tor看起来像这样:

Base(int a) : m_a(a) {}

现在的问题是,类DerivedA和DerivedB都使用某种算法来确定所说的"a",所以不可能执行DerivedA() : Base(a),因为a是在构造函数体中生成的。

对于这样的问题有什么解决方案?

半构建一个对象总是一个坏主意。要么你不构建它,要么你完全构建它。

在您的情况下,最好的解决方案是使用免费功能

int complexCalculation(int a){...}
DerivedA():Base(complexCalculation(a))
{
}

或者您可以选择使用专用(或受保护)静态功能

struct DerivedA{
DerivedA():Base(complexCalculation(a))
{
}
private:
static int complexCalculation(int a){...}
};

您可以创建一个私有静态函数来初始化a

class DerivedA : public Base{
public:
DerivedA() : Base(compute_a())
{
}
private:
static int compute_a() {
//...
}
};

如果可能的话,您还可以将Base转换为模板,并使用Curioly递归模板模式。

template<typename Sub>
struct Base {
int a;
Base() : a(Sub::compute_a()) {}
};
struct DerivedA : Base <DerivedA> {
static int compute_a() {
//...
}
}