静态多态性的模糊性 [英] Ambiguity in static polymorphism
问题描述
这是一个简单的问题,但实际上是一个bug,我很多,我无法找到一个合理的答案。
Quite a simple question actually but one which is bugging me a lot and I'm unable to find a sound answer for it.
对于以下代码,函数调用 d.show();
在 b =& d;
之后的
How is the function call d.show();
NOT ambiguous for the following code AND why does b->show();
after b = &d;
leads to the calling of Base_::show()
?
#include <iostream>
using std::cout;
class Base_
{
public:
void show()
{
cout<<"\nBase Show";
}
};
class Derived_ : public Base_
{
public:
void show()
{
cout<<"Derived Show"<<endl;
}
};
int main()
{
Base_ b;
Derived_ d;
b->show();
d.show();
}
推荐答案
在C ++中。基本上,如果一个类定义了一个函数,它隐藏所有来自父类的具有相同名称的函数。还值得注意的是,如果你有一个 Base _ *
一个派生对象,并调用该函数,它会调用基类版本,因为它不是虚拟的,不会尝试在派生类中找到覆盖的实现。
This is called "Name Hiding" in C++. Essentially, if a class defines a function, it hides all functions with the same name from parent classes. Also worth noting, if you had a Base_*
to a derived object, and called that function, it would call the base classes version as it is not virtual and will not attempt to find overrided implementations in derived classes.
这篇关于静态多态性的模糊性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!