仅在虚拟方法的运行时根据 this 对象的类型确定要调用的函数:
A* a = new B;
a->foo(); //calls B::foo (as long as foo is virtual)
在运行时不会根据函数参数的“真实”类型解析要调用的函数。
A* a = new B;
X* x = new Y;
a->foo(x); //assuming virtual and two overloads, calls B::foo(X*), not B::foo(Y*)
没有内置的双重调度机制(根据两个对象的动态类型同时选择要调用的函数),尽管可以手动实现该模式,如一些帖子所示。
如果您说您总是知道 A& 实际上是 B& 并且不想要强制转换,我的结论是类型将是硬编码已知的编译时,因此您可以尝试“编译时多态性”。 (在这种情况下,A 和 B 甚至不需要关联,只要它们有合适的接口即可。)
class A {};
class B {};
class C: public A {};
void somefunction(const A&, const A&);
void somefunction(const B&, const B&);
template <class T>
void someotherfunction()
{
const T& a1 = T();
const T& a2 = T();
somefunction(a1, a2);
}
int main()
{
someotherfunction<A>();
someotherfunction<B>();
//combine with inheritance and it will still be
//possible to call somefunction(A&, A&) since
//somefunction(C&, C&) is not defined
someotherfunction<C>();
}
现在 a1 和 a2 将真正在一个实例中为 As,而在另一种情况下为 Bs,就选择重载而言。 (我添加了一些 const,否则会更难生成绑定到非 const 引用的东西。)