问题
Quite a simple question actually but one which is bugging me a lot and I'm unable to find a sound answer for it.
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();
}
回答1:
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.
来源:https://stackoverflow.com/questions/32655484/ambiguity-in-static-polymorphism