继承和函数重载

Inheritance and function overloading

我有一些关于继承和函数重载的问题。我写了一些类似下面的接口。现在我试图从派生 class 调用父 class 的某些函数,但它没有按我的预期工作。

为什么可以调用 b.hello() 而不能调用 b.test()

#include <iostream>

using namespace std;

class A {
public:
    void hello() {}
    void test() {}
    virtual void test(int a) {}
};

class B : public A {
public:
    void test(int a) override {}
};

int main() {
    B b;

    // Is possible to call test(int) through B
    b.test(1);

    // Is not possble to call test() through B
    b.test();

    // But, is possible to call hello() through B
    b.hello();
}

Why is it possible to call b.hello() but not b.test()?

在 class 和 AB 中都有名称为 test 的成员函数。但是,classes 是作用域,函数不会跨作用域重载。因此,B 中函数 test 的重载集仅包含 test(int)

另一方面,名称为hello的成员函数只出现在classA中,B继承了这个成员函数。


但是请注意,仍然可以在 b:

上调用 A::test()
B b;
b.A::test();

您还可以使用 using 声明将 A::test 引入 B 引入的范围:

class B: public A {
public:
    using A::test; // brings A::test() to this scope
    void test(int a) override {}
};

现在,A::test() 可以直接在 b 上调用,因为 B 中函数 test 的重载集由 test()test(int):

B b;
b.test();  // calls A::test()
b.test(1); // calls B::test(int)