有没有办法调用基类函数,该函数在使用私有继承的派生类中被覆盖?

Is there a way to call base class function which is over-rided in its derived class that used private inheritance?

本文关键字:继承 派生 覆盖 基类 调用 类函数 函数 有没有      更新时间:2023-10-16

我正在浏览C++中的继承概念并尝试了以下代码:

class base{
public:
void display(int j)
{
cout<<j<< " base "<<endl;
}
};
class derived:private base{
public:
using base::display;
void display(int k)
{
cout<<k<< " derived "<<endl;
}
};
int main()
{
derived obj;
obj.display(10);
//obj.base::display(46); --> cannot be used as base is privately inherited. Also conversion from derived to base cannot happen in this case.
return 0;
}

在上面的情况下,有没有办法通过使用obj从 main 调用基类display函数?

如果基函数没有在派生类中被覆盖,那么通过using(如果基函数在派生中被重载函数隐藏(,我可以在派生中声明它并使用派生类obj调用它。但是在这种情况下,基函数被私有继承覆盖,有没有办法调用基函数?

当我学习C++时,我只是想知道是否有任何方法可以做到这一点(无论任何实际用例如何(。

不是直接的,因为基类中的函数在派生类中是私有的,并且使用声明在这里没有帮助。但是,您可以向派生类添加一个函数,该函数具有不同的名称,用于调用基函数。对导致这种复杂性的设计问题没有评论。

使用虚函数概念可以访问私下继承的基类函数。 使用基类的指针对象,通过将指针对象指向基类对象并调用 display(( 函数来访问继承的成员函数