如何调用父类的同名虚函数

How to call same name virtual functions of parents

#include <stdio.h>  

struct Base
{
    virtual void thatSomething() = 0;
    void doSomething() {thatSomething(); }
};

struct DerOne : Base
{
    virtual void thatSomething() override {std::puts("DerOne"); }
};

struct DerTwo : Base
{
    virtual void thatSomething() override {std::puts("DerTwo"); }
};

struct Joined : DerOne, DerTwo
{
    Joined()
    {
        Base::doSomething();
    }
};

int main()
{
    Joined j;
    return 0;
}

输出:

DerOne

为什么只调用了 DerOne 中的 thatSomething?我希望它被 Joined.

的两个父 类 调用

@hvd 提到通过多重继承我有多个 Base.

的实例

还值得一提:当我翻转Joinedstruct Joined : DerTwo, DerOne)的继承时,我得到

DerTwo

改为输出。

仅在 Joined 构造函数中执行 doSomething() 会给我一个函数调用不明确的错误。

当我使用虚拟继承时,我再次遇到歧义错误。

如果无法通过这种方式调用两个函数,我还有哪些其他选择可以仅用一行不涉及中间函数的代码来实现这一点类 在层次结构中甚至没有隐含的代码行?

快速解决方法就是让 Joined 显式调用两者。 (编辑以覆盖虚函数)

virtual void Joined::thatSomething() override
{
    DerOne::thatSomething();
    DerTwo::thatSomething();
}

如果这不能解决所有问题,那么继承可能不太合适。 Composition 以前用的比较多,先于OOP,现在还是很强大的。

如果您期望在调用 thatSomething() 时发生特定的事情,但您不知道调用哪个,那么 Joined is-a DerOne 和 is-a DerTwo 可能根本不是真的.但是对于 Joined 来说,拥有一个 DerOne 和一个 DerTwo 以及您想要的更多数量要容易得多。

#include <list>
#include <memory>
struct DerHandler
{
    std::list<std::unique_ptr<DerBase>> handlers;

    void addHandler(DerBase *p) { 
        handlers.push_back(std::unique_ptr<DerBase>(p)); 
    }

    void doSomething() { 
        for (std::unique_ptr<DerBase> &rp : handlers)
            rp->thatSomething();
    }
};

struct Joined : DerHandler {
    Joined(){
        addHandler(new DerOne);
        addHandler(new DerTwo);
    }
};