如何调用未在派生类中定义的基类函数?

pok*_*che 2 c++

我一直认为基类的公共方法确实被派生类继承,甚至认为派生类没有定义该特定方法.例如

#include <iostream>

using namespace std;


    class A {
    public:
        int f() { cout << 3; return 0;}
        int f(int x) {cout << x; return 0;}
    }; 

    class B: public A {
    public:
        int f() {std::cout << 5; return 0;}

    };


    int main(){
       B ob;
       ob.f(7); 

       return 0;
    }
Run Code Online (Sandbox Code Playgroud)

我期待结果是:7,但我得到编译错误说

" 错误:函数调用的参数太多,预期为0,有1;你的意思是'A :: f'吗? "

我知道错误试图说的是什么,但我很困惑,没有调用Base类的功能.

Gau*_*gal 6

在派生类中重载方法会隐藏所有基类版本.即使签名不同.如果与基类中的名称相同的方法存在于派生类中,则您将无法直接调用基类版本.

你可以做

  ob.A::f(7);
Run Code Online (Sandbox Code Playgroud)