在c ++中,如果你有以下
struct Base
{
};
struct Derived1 : Base
{
};
struct Derived2 : Derived1
{
};
struct Derived3 : Derived2
{
};
void f(const Derived2&)
{
std::cout << "Derived2" << std::endl;
}
void f(const Derived1&)
{
std::cout << "Derived1" << std::endl;
}
int main()
{
f(Derived3());
return 0;
}
f(Derived3())调用“void f(const Derived2&amp;)”是什么原因?是因为它在Derived3的对象层次结构中比Derived1更接近吗?
答案 0 :(得分:0)
请参阅overload resolution rules了解c ++。
当尝试解析要调用的函数时,如果参数类型中没有直接匹配,则编译器必须对参数所需的转换进行排名,以便选择最佳候选者。
对于与继承层次结构中的对象相关的转换:
3) If Mid is derived (directly or indirectly) from Base, and Derived is derived (directly or indirectly) from Mid
a) Derived* to Mid* is better than Derived* to Base*
b) Derived to Mid& is better than Derived to Base&
c) Base::* to Mid::* is better than Base::* to Derived::*
d) Derived to Mid is better than Derived to Base
e) Mid* to Base* is better than Derived* to Base*
f) Mid to Base& is better than Derived to Base&
g) Mid::* to Derived::* is better than Base::* to Derived::*
h) Mid to Base is better than Derived to Base
案例b)适用于您的示例。