Pav*_*vel 1 c++ inheritance overloading
我f()在类A和子类B中有方法,我添加方法f(int).所以我都f()和f(int)中B,如果我的理解对不对.我想f()在另一种方法中使用,B但这是一个错误.
class A {
public:
int f() {
return 3;
}
};
class B : public A {
int x;
public:
int f(int a) {
return a * 2;
}
void g() {
x = f();
// no matching function for call to 'B::f()'
// candidate is 'int B::f(int)'
}
};
Run Code Online (Sandbox Code Playgroud)
如果我删除f(int)从B它会奏效.
所以我都
f()和f(int)中B,如果我的理解对不对.
不,A::f()隐藏在范围内B.因为f可以在类的范围内找到命名的成员函数B,然后名称查找将停止,所以f将找不到基类版本并考虑重载解析.最后编译失败,因为函数参数不匹配.这是一种隐藏的名字.
您能介绍A::f通过using.
class B : public A {
int x;
public:
using A::f;
int f(int a) {
return a * 2;
}
void g() {
x = f();
}
};
Run Code Online (Sandbox Code Playgroud)
如果我删除
f(int)从B它会奏效.
然后名称查找在类的范围内失败,B将检查更多的范围并将A::f在基类的范围内找到A,然后它运行良好.
请参阅非限定名称查找