由于多个抽象基类,实现两个具有相同名称但不同的非协变返回类型的函数

Tar*_*Tar 6 c++ overriding virtual-functions multiple-inheritance abstract-base-class

如果我有两个抽象类定义一个具有相同名称但不同的非协变返回类型的纯虚函数,我如何从这些函数派生并为它们的函数定义一个实现?

#include <iostream>

class ITestA {
    public:
        virtual ~ITestA() {};
        virtual float test() =0;
};

class ITestB {
    public:
        virtual ~ITestB() {};
        virtual bool test() =0;
};

class C : public ITestA, public ITestB {
    public:
    /* Somehow implement ITestA::test and ITestB::test */
};


int main() {
    ITestA *a = new C();
    std::cout << a->test() << std::endl; // should print a float, like "3.14"
    ITestB *b = dynamic_cast<ITestB *>(a);
    if (b) {
        std::cout << b->test() << std::endl; // should print "1" or "0"
    }
    delete(a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

只要我不直接调用C :: test()就没有任何含糊之处,所以我认为它应该以某种方式工作,我想我还没找到正确的符号.或者这是不可能的,如果是这样:为什么?

Tar*_*Tar 3

好吧,这是可能的,而且方式也不算太难看。我必须添加额外的继承级别:

 ITestA       ITestB     <-- These are the interfaces C has to fulfill, both with test()
    |           |
ITestA_X     ITestB_X    <-- These classes implement the interface by calling a
    |           |             function with a different name, like ITestA_test
    \__________/              which is in turn pure virtual again.
         |
         C               <--  C implements the new interfaces
Run Code Online (Sandbox Code Playgroud)

现在 C 没有 function test(),但是当将 a 转换C*为 an时,将使用inITestA*的实现。当将其转换为 时,即使通过来自 的dynamic_cast ,也将使用的实现。以下程序打印:3.14 0test()ITestA_testITestB*ITestA*ITestB_test

#include <iostream>

class ITestA {
    public:
        virtual ~ITestA() {};
        virtual float test() =0;
};

class ITestB {
    public:
        virtual ~ITestB() {};
        virtual bool test() =0;
};

class ITestA_X : public ITestA {
    protected:
        virtual float ITestA_test() =0;
        virtual float test() {
            return ITestA_test();
        }
};

class ITestB_X : public ITestB {
    protected:
        virtual bool ITestB_test() =0;
        virtual bool test() {
            return ITestB_test();
        }
};

class C : public ITestA_X, public ITestB_X {
    private:
        virtual float ITestA_test() {
            return 3.14;
        }
        virtual bool ITestB_test() {
            return false;
        }
};

int main() {
    ITestA *a = new C();
    std::cout << a->test() << std::endl;
    ITestB *b = dynamic_cast<ITestB *>(a);
    if (b) {
        std::cout << b->test() << std::endl;
    }
    delete(a);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您能想到这有什么缺点吗?