joz*_*yqk 5 c++ inheritance overloading
有人可以解释一下这里发生了什么.为什么编译器在A类中看不到没有参数的hello()?
struct A {
virtual void hello() {}
virtual void hello(int arg) {}
};
struct B : A {
virtual void hello(int arg) {}
};
int main()
{
B* b = new B();
b->hello();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
g ++ main.cpp
main.cpp: In function ‘int main()’:
main.cpp:13:11: error: no matching function for call to ‘B::hello()’
main.cpp:13:11: note: candidate is:
main.cpp:7:15: note: virtual void B::hello(int)
main.cpp:7:15: note: candidate expects 1 argument, 0 provided
Run Code Online (Sandbox Code Playgroud)
因为你的覆盖hello(int arg)隐藏了具有相同名称的其他功能.
你可以做的是明确地将这些基类函数引入子类:
struct B : A {
using A::hello; // Make other overloaded version of hello() to show up in subclass.
virtual void hello(int arg) {}
};
Run Code Online (Sandbox Code Playgroud)