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

问题描述 投票:-5回答:3

私人成员也是继承的吗?

为什么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是私有变量,它都运行良好。

c++ pointers inheritance private
3个回答
1
投票

基类的所有成员,私有的和公共的都是继承的(否则继承本身就是 - 双关语意图 - 被破坏),但它们保留了私有访问修饰符。

由于你的例子中的继承本身是公开的,因此inh拥有base的公共成员,因为它是自己的公共成员 - 而a.show()是完全合法的。


0
投票

调用访问私有数据成员的函数是很好的。 private只是意味着您无法在课堂外访问数据成员


0
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.