【问题标题】:Inheritance and function overloading [duplicate]继承和函数重载
【发布时间】:2020-03-06 14:46:54
【问题描述】:

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

为什么可以调用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();
}

【问题讨论】:

  • 你得到什么错误?你尝试了哪些改变?
  • 询问代码和错误时,请显示真实代码(您缺少;,这让我觉得您的真实代码不同)和错误。
  • 因为编译器试图在B 中找到test 函数,当它在那里找到它时,发现你试图在没有参数的情况下调用它。

标签: c++ inheritance overloading


【解决方案1】:

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

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

另一方面,名为 hello 的成员函数仅存在于类 A 中,而 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)

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    相关资源
    最近更新 更多