继承函数是否适用于 C++ 中的基类元素或派生类元素?

do inherited functions work on base class elements or derived class elements in c++?

本文关键字:元素 派生 基类 是否 函数 适用于 C++ 继承      更新时间:2023-10-16

>假设我有两个类,这样:

class base
{
int hello;
public:
base
{
hello=5;
}
void show()
{
cout<<hello;
}
};
class derived:public hello
{
int hello;
public:
derived()
{
hello=2;
}
show();
};

现在我想知道它会显示 2 还是 5 个? 如果是这样,那么为什么以及如何让它反过来?

不,因为您有两个不同且独立的变量helloderived类中的那个有点"覆盖"base类中的那个。

如果你想让它工作,你只需要有一个变量。

简短的回答是,公共继承模拟了 is-a关系。派生类是一个基类。派生类的构造函数将隐式调用基类的构造函数。