使用派生的[C++]生成的参数初始化基类
Initializing base class with parameters generated by derived [C++]
我有一种情况,我有一些基类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() {
//...
}
}
相关文章:
- C++转换参数初始化问题
- 在构造函数中使用可变参数初始化 std::tuple
- 类模板专用化演绎是否应该考虑演绎指南参数初始化?
- 如何通过参数初始化构造函数中的数组?
- 在模板类中使用"this"会导致参数初始化错误
- 如何使用一些参数初始化动态分配的数组中的对象
- 使用模板参数初始化静态 const 成员
- 基于模板参数初始化静态字符
- 使用参数初始化
- 使用参数包参数初始化"std::array"
- 从按值构造函数参数初始化的引用成员
- 使用派生的[C++]生成的参数初始化基类
- 一个C++默认参数可以用另一个参数初始化吗
- 如何用功能指针作为参数初始化静态成员的模板
- 用参数初始化另一类构造函数中的对象
- C :如何通过其构造函数的参数初始化类内部矩阵的尺寸
- C++:基于构造函数参数初始化向量
- 正在使用模板参数初始化stl类
- 如果类 A 修改其构造参数,我可以使用常量参数初始化 const A 吗?
- 使用结构非类型可变参数模板参数初始化结构的字符串数据成员