c++ - union 虚拟继承

标签 c++ inheritance

我正在尝试实现以下继承关系。

         Variable
       /         \
... GlobalVar  LocalVar ...
       \         / (either)
       ExtendedVar // Essentially with more fields

我基本上希望它扩展 Variable 的子类之一,并在运行时做出选择。虚拟继承并不能完全解决问题。如果 ExtendedVar 继承了 GlobalVarLocalVar 并且当我需要调用一些成员函数时,我无法指定要使用哪个基类功能。

此代码似乎有效。

class ExtendedVar : public Variable /* ExtendedVar is-a Variable */ {
    Variable& var; // wraps a var in it. This is the var to extend.
    std::string some_field;
}

但它在继承中附带了一个不必要的 A 拷贝。或者我可以有更多的类,例如 ExtendedGlobalVarExtendedLocalVar,这显然不利于维护。

有更好的选择吗?

最佳答案

I basically want it to extend one of the subclass of Variable, and the choice is made at run time.

要具有运行时多态性,您必须间接引用一个对象。基地不能是间接的,但普通成员(member)可以。因此,您建议的继承是不可能的,但组合是:

struct ExtendedVar {
    std::unique_ptr<Variable> var;
};

Or I could have a few more classes like ExtendedGlobalVar and ExtendedLocalVar, which are obviously bad for maintainence.

如果这是一个选项(即使是一个糟糕的选项),那么听起来不必在运行时选择基数。

在这种情况下,您可以使用模板生成具有您选择的基础的类,而无需单独维护每个变体:

template <class Base>
struct ExtendedVar : Base {
    // things common to all extended variables
};

ExtendedVar<GlobalVar> an_extended_global_variable;

关于c++ - union 虚拟继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45439042/

相关文章:

php - 如何在php中实现鸡鸡蛋鸟类接口(interface)问题

inheritance - 从 Nim 中的序列继承

c++ - 将 'typedef' 从基类传播到 'template' 的派生类

c++ - 为什么 boost::filesystem 中止而不是抛出异常?

c++ - 删除 vector 中的对象

c++ - 如何在 C++ 中明确数据所有权

javascript - 在 JavaScript 中进行 Prototype 面向对象编程的最佳方法

c++ - 根据大小扣除类型 C++

c++ - 为什么这个程序抛出 'std::system_error' ?

c++ - 当基类没有虚拟析构函数时为空子类 - 删除基指针的不利影响?