隐藏在c++中的函数

Function hiding in c++

我尝试了一些在 C++ 中隐藏函数的概念。 因此,在派生 class 中,我使用范围解析运算符 using base::fun 在派生 class 中提供基础 class 的范围。我的 objective 是打印 cout<<" base "<< x; 但输出只打印派生的 class cout。有什么原因以及如何解决?即它应该打印基础和派生的 class 值。我是 c++ 的新手,很抱歉任何 mistakes.The 代码如下所示:

#include <stdio.h>
#include <iostream>
using namespace std;

class base
{
public:
int fun(int x)
{
    cout<<" base "<< x;
    return x;
}
};
class derived:public base
{
public:
using base::fun;
void fun(int a)
{
    cout<<" derived "<< a;
}
};

int main()
{
    derived d;
    d.fun(10);
    return 0;
}

it should print both base and derived class value

为什么你认为应该这样做?有一个函数调用, 所以理论上,它应该是 derived::funbase::fun,而不是两者。由于 dderived 类型,因此 derived::fun 被调用。

it should print both base and derived class value

没有。只会选择和调用一个函数。那么问题是应该选择哪一个。本例选择derived::fun;因为 using declaration,

If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

您可以通过明确指定来调用基数:

d.base::fun(10);

LIVE