继承的类对象如何使用私有数据成员

How private data member is used by an inherited class object?

本文关键字:数据成员 何使用 对象 继承      更新时间:2023-10-16

私有成员也是继承的吗?

为什么 get(( 函数能够读取变量 n

#include <iostream>
using namespace std;
class base
{
    int n;
public:
    void get()
    {
        cin >> n;
    }
    int ret()
    {
        return n;
    }
};
class inh : public base
{
public:
    void show()
    {
        cout << "hi";
    }
};
int main()
{
    inh a;
    a.get();
    a.show();
    return 0;
}

无论 n 是私有变量的事实如何,它都能正常工作。

类的所有成员,私有和公共都是继承的(否则继承本质上是 - 双关语 - 破坏(,但它们保留私有访问修饰符。

由于示例中的继承本身是公共的,因此inh base的公共成员作为自己的公共成员 - a.show()是完全合法的。

调用访问私有数据成员的函数是可以的。 private只是意味着您无法在类之外访问数据成员本身

您不访问主中的任何私有成员:

int main()
{
  inh a;
  a.get(); // << calling a public method of the base class. OK!
  a.show(); // calling a public method of the inh class. OK!
  return 0;
}
只能从基类成员

访问基类的私有成员:

class base
{
  int n;
public:
  void get()
  {
    cin >> n; // writing in my private member. OK!
  }
  int ret()
  {
    return n; // returning value of my private member. OK!
  }
};

这会导致主要问题:

 inh a;
 a.n = 10; // error
 base b;
 b.n = 10; // error