c++ - 如何轻松替换基类

标签 c++ class oop abstract-class

我有以下类层次结构

class classOne
{
    virtual void abstractMethod() = 0;
};

class classTwo : public classOne
{
};

class classThree : public classTwo
{
};  

所有 classOne、classTwo 和 classThree 都是抽象类,我还有另一个类定义纯虚方法

class classNonAbstract : public classThree
{
    void abstractMethod();

    // Couple of new methods
    void doIt();
    void doItToo();
};

现在我需要它不同......我需要它就像

class classNonAbstractOne : public classOne
{
    void abstractMethod();

    // Couple of new methods
    void doIt();
    void doItToo();
};

class classNonAbstractTwo : public classTwo
{
    void abstractMethod();

    // Couple of new methods
    void doIt();
    void doItToo();
};

class classNonAbstractThree : public classThree
{
    void abstractMethod();

    // Couple of new methods
    void doIt();
    void doItToo();
};

但是所有非抽象类都有相同的新方法,具有相同的代码......并且我想避免将所有方法及其代码复制到每个非抽象类。我怎样才能做到这一点?

希望这是可以理解的......

最佳答案

template<class Base>
struct Concrete : Base {
  void abstractMethod();

  void doIt() {
    // example of accessing inherited members:
    int n = Base::data_member; // or this->data_member
    n = Base::method(); // non-virtual dispatch
    n = this->method(); // virtual dispatch

    // since Base is a template parameter, 'data_member' and 'method' are
    // dependent names and using them unqualified will not properly find
    // them
  }
  void doItToo();
};

typedef Concrete<classOne> classNonAbstractOne; // if desired, for convenience

确保为您的抽象基类提供虚拟公共(public)析构函数或使析构函数 protected (这样它不必是虚拟的,但仍然可以是)。

因为必须使用查找的名称来解析模板,但还不知道 Base 到底是什么,因此您需要使用 Base::memberthis ->member 访问继承的成员。

关于c++ - 如何轻松替换基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2794637/

相关文章:

html - jade - 创建多个 html 元素

php - SQL 查询还是面向对象的设计?

c++ - 从模板 Callable 生成 promise

C++ 我可以使用 string::at 分配一个 int 吗?

java - 处理类之间的事件

oop - 面向对象编程中 null 的最佳替代方法是什么?

php - 鉴别器列可以成为 Doctrine2 中主键的一部分吗?

C++数组通过函数引用初始化

c++ - 使用虚拟保护方法继承

php - 如何将方法的默认参数设置为类成员