c++ - 避免重复代码

标签 c++

请引用下面的例子。

using namespace std;
//Base interface
class IBase
{
public:
    virtual void BaseMethod1() = 0;

    virtual void BaseMethod2() = 0;
};

class IEntity1 : public IBase
{
public:
    virtual void Entity1Method1() = 0;

    virtual void Entity1Method2() = 0;
};

class Entity1 : public IEntity1
{
public:
    Entity();
//IBaseMethods
    void BaseMethod1();
    void BaseMethod2();
//IEntityMethods
    void Entity1Method1();
    void Entity1Method2();
//EntityMethods
    void Method1();
    void Method2();
};

在上面的示例中,对于从 IBase 派生的所有其他实体,需要实现 BaseMethod1() 和 BaseMethod2()。因此会出现大量代码重复?无论如何,我们可以避免在从它派生的实体中冗余实现 IBase 方法吗?

最佳答案

您可以结合使用虚拟继承和默认基实现类来封装您的默认基行为,并使其仅由您想要的具体类继承,如下所示:

using namespace std;
//Base interface
class IBase
{
public:
    virtual void BaseMethod1() = 0;
    virtual void BaseMethod2() = 0;
};

class IEntity1 : virtual public IBase
{
public:
    virtual void Entity1Method1() = 0;
    virtual void Entity1Method2() = 0;
};

class BaseImpl : virtual public IBase
{
public:
    virtual void BaseMethod1()
    {
        ...
    }
    virtual void BaseMethod2()
    {
        ...
    }
}

class Entity1 : public IEntity1, public BaseImpl
{
public:
    Entity1();
//IEntityMethods
    void Entity1Method1();
    void Entity1Method2();
//EntityMethods
    void Method1();
    void Method2();
};

但是,有一个 runtime cost与虚继承有关。多重继承也伴随着一些结构性问题,例如基类构建。

您甚至可以从模板类中获得一些乐趣,使您的类组合更加模块化:

template<typename TEntity, typename TBaseImpl>
class ConcreteEntity: public TEntity, public TBaseImpl
{
public:
    ConcreteEntity() {}
};

class ConreteEntity1 : public ConcreteEntity<IEntity1, BaseImpl>
{
public:
    ConreteEntity1();

//IEntityMethods
    void Entity1Method1();
    void Entity1Method2();
//ConreteEntity1 Methods
    void Method1();
    void Method2();
};

关于c++ - 避免重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21669489/

相关文章:

c++ - 暂时将指针设为 NULL 有什么意义吗?

c++ - 如何在类中 (*.cpp) 而不是 (*.h) 中定义结构

c++ - 接受对象作为参数的构造函数发生了什么?

python - BoostPython 和 CMake

c++ - 将多个文件硬链接(hard link)到一个文件

c++ - 回溯N皇后算法

c++ - 如何在容器项目的字段上创建迭代器?

c++ - 说明/讨论为什么不强制 std::sort 使用 std::swap

c++ - 找到两个 vector 相对于 vector 对象的两个成员的交集的有效方法

c++ - 如何在另一个函数中使用一个函数?