可能的重复:
C++重载解析
为什么派生类中的重写函数会隐藏基类的其他重载?
为什么以下示例:
class A {
public:
void f(int x){ }
};
class B : public A {
public:
void f(float a, int b){ }
};
int main(){
B *b = new B;
b->f(1);
};
Run Code Online (Sandbox Code Playgroud)
原因:
test.cpp:在函数'int main()'中:test.cpp:13:错误:没有匹配函数来调用'B :: f(int)'test.cpp:8:注意:候选者是:void B: :f(float,int)
f(int)并f(float, int)有不同的签名.为什么会导致错误?
编辑
我明白它藏起来了.我在问为什么会这样?
从本质上讲,您不会重载基类方法; 通过重新定义方法f,您隐藏了基类方法.您可以通过将其明确地包含在子类范围中来防止这种情况:
class B : public A {
public:
using A::f;
void f(float a, int b){ }
};
Run Code Online (Sandbox Code Playgroud)