【发布时间】:2012-11-19 22:00:31
【问题描述】:
也许我有两个函数名称和参数相同但返回值不同的接口:
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
【问题讨论】:
-
你为什么想要这样的东西?
-
也许他不拥有A和B;但必须使 C 实现两者。似乎是一个合理的问题
-
这在 C++ 中是不可能的(不是你编写的那样)。函数由它们的参数类型而不是它们的返回类型来标识。
-
仅供参考 - C# 让你说 A:foo , B:foo 在这种情况下(显式实现)
标签: c++ visual-studio-2012 multiple-inheritance