C++如何从具有不同返回类型的接口继承多个?

use*_*009 8 c++ multiple-inheritance visual-studio-2012

也许我有两个具有相同功能名称和参数的接口,但具有不同的返回值:

struct A { virtual void foo() = 0; };
struct B { virtual int foo() = 0; };
Run Code Online (Sandbox Code Playgroud)

如何定义继承此接口的类C(如果可能的话)?例如,我写了一些未编译的伪代码:

// this code is fake, it doesn't compiled!!
struct C : A, B
{
    // how to tell compiler what method using if referenced from C?
    using void foo();  // incorrect in VS 2012
    // and override A::foo() and B::foo()?
    virtual void foo() { std::cout << "void C::foo();\n"; } // incorrect
    virtual int foo() { std::cout << "int C::foo();\n"; return 0; } // incorrect
 }
 // ... for use in code
 C c;
 A &a = c;
 B &b = c;
 c.foo();     // call void C::foo() when reference from C instance
 a.foo();     // call void C::foo() when reference from A instance
 b.foo();     // call int C::foo() when reference from B instance
Run Code Online (Sandbox Code Playgroud)

Som*_*ame 4

这是不可能的,但不是因为多重继承。由于fooin class的无效重载而产生歧义C。您不能同时拥有两者int foo(),并且void foo()由于返回类型不是函数签名的一部分,因此编译器将无法解析对foo. 您可以将接口视为 和A类的联合B,因此从逻辑上讲,问题在实际继承之前就已经存在。由于从编译器的角度来看,AB是两种不同且不相关的类型,因此编译它们时没有问题,并且错误会延迟到类中实际统一的时刻C

请在此处查看有关函数签名和重载的更多信息:返回类型是函数签名的一部分吗?