This question already has answers here:
Why does an overridden function in the derived class hide other overloads of the base class?
(4个答案)
3年前关闭。
输出:
虽然我仍然可以通过
(4个答案)
3年前关闭。
struct A{
void foo(A a){}
virtual void foo(int c=1){}
};
struct B : public A{
void foo(int c){}
};
int main(){
A* object = new B();
object->foo();
((B*)(object))->foo(*object);
}
输出:
test_test.cpp: In function ‘int main()’:
test_test.cpp:14:36: error: no matching function for call to ‘B::foo(A&)’
((B*)(object))->foo(*object);
^
test_test.cpp:8:14: note: candidate: virtual void B::foo(int)
void foo(int c){}
^
test_test.cpp:8:14: note: no known conversion for argument 1 from ‘A’ to ‘int’
虽然我仍然可以通过
((B*)object)->A::foo(*object)
使用 A::foo ,但我想听听它为何如此运行的故事。 最佳答案
因为这是name lookup的规则。如果在当前作用域(例如B
类)上找到了该名称,则名称查找将停止,不会检查其他外部作用域(例如A
类)。名称查找过程将不考虑函数的参数,而仅考虑名称。
根据找到的名称执行名称查找重载解析后,您得到了显示的错误。
关于c++ - 为什么重写的方法会隐藏所有具有相同名称的方法,而不管其参数为何,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46449141/