繁体   English   中英

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

[英]C++ How to multiple inherits from interfaces with different return types?

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

struct A { virtual void foo() = 0; };
struct B { virtual int foo() = 0; };

如何定义继承此接口的类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

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

在这里查看有关函数签名和重载的更多信息:函数签名的返回类型是否部分?

可以做的是将所有共享内容放入virtual基础中,比如说C_base并覆盖辅助类中的冲突virtual函数。 由于C的共享内容在C_base很容易获得, C_base基本上就像在派生最多的C 最后,你只是因为班级把事情拉到一起C类:

struct A { virtual void foo() = 0; };
struct B { virtual int foo() = 0; };

struct C_base { int all_data; };

struct A_aux: virtual C_base, A {
    void foo() { std::cout << "A_aux::foo()\n"; }
};

struct B_aux: virtual C_base, B {
    int foo() { std::cout << "B_aux::foo()\n"; return 0; }
};

struct C : A_aux, B_aux
{
    using A_aux::foo;
};

您可以明确限定。

class C : A, B {
public:
    void A::foo() { ... }
    int B::foo() { ... }
};

编辑:

这似乎是MSVC扩展,而不是标准。

使用相同的签名覆盖虚函数的返回类型是不可能的(如@ icepack的答案所解释的)。

另一种方法可能是使用模板基类声明foo() ,返回类型指定为模板参数,并为具体的返回参数类型提供特化。

这将是@DietmarKühl的提议的概括。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM