隐藏在C ++中的函数

我尝试了一些在C ++中隐藏函数的概念。 因此,在派生类中,我使用了作用域解析运算符,使用base :: fun在派生类中提供了基类的作用域。我的目标是打印“ cout <<” base“ << x;”但是输出仅输出派生类cout。有什么原因以及如何解决?即它应该同时打印基类和派生类的值。我是C ++的新手,对不起任何错误。代码如下所示:

#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;
}
评论
情断心却相
情断心却相
它应该同时打印基类和派生类的值

Why do you think it should? There is a single function call, so theoretically, it should be either derived::fun or base::fun, not both. Since d is of type derived then derived::fun gets called.

点赞
评论