c++ - 我应该避免多重实现继承吗?

标签 c++ inheritance multiple-inheritance

<分区>

我想为可以从外部方法/类访问的类的不同属性定义接口(interface)。

  • 我使用多重实现继承(= 从具体类继承而不是接口(interface)继承),这被认为是一种不好的做法 ( point 3 from here )。

  • 我使用继承来重用代码。如前所述here , 最好使用组合而不是继承来重用代码。但是通过组合,我所有的 MyObj1,MyObj2,...,MyObj1000 都将具有相同的 get 和 set 方法,而我很少需要重新实现它们。

这个场景是否完美地说明了代码重用的多重实现继承是好的,还是这段代码完全错误,我应该使用一些聪明的语法/模式来避免这种设计? 我问这个问题是因为我相信后者。

#include <string>
#include <iostream>

// interface of object with name
class BaseName {
public:
    virtual void setName(const std::string& val) { name = val; }
    virtual std::string getName() const { return name; }
private:
    std::string name;
};

// user of interface of objects with name
void nameUser(BaseName* b) {
    std::cout << b->getName() << std::endl;
}

// interface of object with id
class BaseID {
public:
    virtual void setID(int val) { id = val; }
    virtual int getID() const { return id; }
private:
    int id = 0;
};

// user of interface of objects with id
void idUser(BaseID* b) {
    std::cout << b->getID() << std::endl;
}

class MyObj1 : public BaseID, public BaseName {
public:
    void setName(const std::string& val) override { 
        /* update internal state that depends on name. this is why "virtual" is required */
        BaseName::setName(val);
    }

    /* methods and fields specific to MyObj1 */
};

// MyObj2,...,MyObj999

class MyObj1000 : public BaseID, public BaseName {
public:
    /* methods and fields specific to MyObj1000 */
};

int main() {
    MyObj1 o1;
    o1.setName("xxx");
    o1.setID(18);

    MyObj1000 o2;
    o2.setName("yyy");
    o2.setID(-738);

    nameUser(&o1);
    nameUser(&o2);
    idUser(&o1);
    idUser(&o2);
}

最佳答案

只有当你的派生类是一个基类时,你才应该继承,也就是说它在你的系统中作为它继承的类起作用是有意义的。多重继承出现的地方是派生类存在于多个“域”中,例如,您可能有一个 bird 类,它也是 serializable,您可以继承 animalserializable,并且可以从每个继承实现。

但是您有 1000 个派生类的事实是 Code Smell大部头书。您或许应该退后一步,更广泛地审视您的设计和您想要实现的目标。对此了解更多有助于我们给出更好的答案。

关于c++ - 我应该避免多重实现继承吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53048255/

相关文章:

c++ - 具有显式参数和 sizeof 的 Variadic 模板... Visual Studio 2013

C++ 使用类标记数学表达式

c++ - 通过使用范围解析避免多重继承引起的歧义

C++ 虚拟继承不起作用,如何使用多个父级成员?

c++ - Qt-Frameless 窗口和 OS 按钮

c++ - 当操作系统无法分配内存时,使用 STL 的应用程序是否应该容易发生内存泄漏?

c++ - 错误 : call of overloaded is ambiguous

c# - 为什么 AcquireRequestState 隐藏 Inherited HttpApplication.AcquireRequestState 而 Application_Start 则不隐藏?

c++ - 我的菱形继承(钻石问题)编译器错误无法解决?

python 3.7.4 : inheriting both ABC and concrete class