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

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

私有成员是否也是继承

为什么 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 是私有变量,但它工作正常。

base class 的所有成员,private 和 public 都是继承的(否则继承将是 inherently - 双关语 - 损坏),但它们保留私有访问修饰符。

由于您的示例中的继承本身是 public,inh 拥有 base 的 public 个成员,因为它拥有 public 个成员 - 并且 a.show() 是完全合法的。

可以调用访问私有数据成员的函数。 private 只是意味着您无法访问 class

之外的数据成员本身

您没有访问主目录中的任何私有成员:

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 成员访问基 class 的私有成员:

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