作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
也许我有两个函数名和参数相同但返回值不同的接口(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)视为 A
和 B
类的 union ,因此从逻辑上讲,问题在实际继承之前就已经存在。由于从编译器的角度来看 A
和 B
是两种不同且不相关的类型,因此在编译它们时没有问题,并且错误会延迟到类 中的实际统一点C
.
在此处查看有关函数签名和重载的更多信息:Is the return type part of the function signature?
关于C++如何从具有不同返回类型的接口(interface)进行多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13463048/
我是一名优秀的程序员,十分优秀!