将方法添加到名为与继承方法相同的子类

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它会奏效.

son*_*yao 5

所以我都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,然后它运行良好.

请参阅非限定名称查找