向与继承方法同名的子 class 添加方法

Adding a method to a child class named same as an inherited method

我在 class A 中有方法 f(),在子 class B 中我添加了方法 f(int)。因此,如果我理解正确的话,我在 B 中同时拥有 f()f(int)。我想在 B 的另一种方法中使用 f() 但这是一个错误。

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)'
    }
};

如果我从 B 中删除 f(int),它将起作用。

So I have both f() and f(int) in B if I understand right.

不,A::f() 隐藏在 B 的范围内。因为可以在 class B 的范围内找到名为 f 的成员函数,然后名称查找将停止,基础 class 版本 f 将不会' t 被发现并考虑过载解决方案。最后编译失败,因为函数参数不匹配。是一种隐姓埋名。

您可以通过using介绍A::f

class B : public A {
    int x;
public:
    using A::f;
    int f(int a) {
        return a * 2;
    }
    void g() {
        x = f();
    }
};

If I remove f(int) from B it will work.

然后名称查找在 class B 的范围内失败,将检查进一步的范围并且将在基础 class 的范围内找到 A::f A,那么效果不错

Unqualified name lookup

您可以使用范围解析运算符::

x = f();替换为x = A::f();

class A {
public:
    int f() {
        return 3;
    }
};

class B : public A {
    int x;
public:
    int f(int a) {
        return a * 2;
    }
    void g() {
        x = A::f();
    }
};