gpt4 book ai didi

C++如何从具有不同返回类型的接口(interface)进行多重继承?

转载 作者:可可西里 更新时间:2023-11-01 17:41:51 26 4
gpt4 key购买 nike

也许我有两个函数名和参数相同但返回值不同的接口(interface):

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

如何定义继承此接口(interface)的 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。您可以将接口(interface)视为 AB 类的 union ,因此从逻辑上讲,问题在实际继承之前就已经存在。由于从编译器的角度来看 AB 是两种不同且不相关的类型,因此在编译它们时没有问题,并且错误会延迟到类 中的实际统一点C.

在此处查看有关函数签名和重载的更多信息:Is the return type part of the function signature?

关于C++如何从具有不同返回类型的接口(interface)进行多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13463048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com