如何将基类替换为派生基类
How to replace base class with derived base class
我正在开发一个API,其中类A派生为类B。
如果 API 用户希望在应用程序级别扩展 A 类和 B 类的功能,那么就会出现问题。
假设应用程序用户提出类 AX 扩展类 A,类 BX 扩展类 B。在这种情况下,用户不会获得类 BX 的预期行为,因为类 B 的基类是类 A 而不是类 AX。
思想:应用程序用户可以同时使用 B 类和 AX 类扩展类 BX,但在这种情况下,我认为会有已知的菱形行为。
我想知道,解决此问题的任何标准方法。
从模板参数继承的类也是一种选择。 伪代码:
class A;
template<typename WhichA>
class B : public WhichA;
class AX : public A;
class BX : public B<AX>;
你的问题有点模糊。无论如何,我建议您阅读C++常见问题解答25和问题25.5。问题25.5和25.6讨论了一些备选办法。
。但在这种情况下,我认为会有已知的钻石行为
那么问题出在哪里呢? virtual
继承是为了解析这种菱形图案。
如果A
的孩子实际上是继承的,那么我认为没有任何问题,除非改变设计。
class InterfaceA;
class InterfaceB;
class A : public InterfaceA;
template<class AType>
class B_Template : public InterfaceB, public AType;
// Below is same as class B in example
// Users can use B as if it was class B
typedef B_Template<A> B;
// User can extend A
class AX : A;
// User can extend B any way they want (you can't police this)
// but the way you wanted in the question was:
class BX : B_Template<AX>; // Inherits of the extended AX
这解决了您的问题,但正如评论中指出的那样,您应该考虑依赖注入而不是继承。
此外,接口类并不是真正需要的,但它可以清楚地表明基类上的协定是什么 - 即模板参数 AType 必须满足 InterfaceA。
相关文章:
- 指向基类派生类的 std::unique_ptr 的指针
- 从多个模板化基类派生时出现"隐藏重载的虚函数"警告
- 从模板基类派生是否在派生类声明的点实例化模板
- 使从一个基类派生的类能够使用继承的受保护成员
- C++多态性访问基类派生类字段
- C++派生类的设置属性到从同一基类派生的未知类对象
- 使用void* 参数定义纯虚函数的抽象基类.派生类匹配参数是指向某种类型的指针
- 在C++中,如何使用将保存从基类派生的任何对象的类成员
- 如何测试从依赖于外部系统的外部基类派生的类
- 如何从模板基类派生非模板类
- 在派生类中使用声明并不能隐藏从基类派生的相同函数
- 从具有静态结构的基类派生
- 具有从 c++ 中的非模板基类派生的模板类的事件系统
- C++ 调用从基类派生的覆盖函数
- 不清楚如何在从抽象基类派生的类中实现运算符重载
- 如何正向声明从正向声明的模板基类派生的类
- 是否可以从 std::enable_shared_from_this 和抽象基类派生
- 多态性c++,试图访问从抽象基类派生的类的成员函数
- C++多重继承,基类派生自同一类
- 基类派生类访问-如何