【问题标题】:How private data member is used by an inherited class object?继承的类对象如何使用私有数据成员?
【发布时间】:2019-09-03 14:19:51
【问题描述】:

私人成员是否也被继承

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

【问题讨论】:

  • 您究竟为什么预期会出现错误?
  • 因为私有数据成员没有被继承
  • 你从哪里收集到的?
  • 私人数据成员不应该按照我的老师继承,但是当我尝试上面的代码时它起作用了。这就是我来这里聚会的原因
  • @Manish 所有成员都是继承的,但私有成员不能访问派生类。

标签: c++ pointers inheritance private


【解决方案1】:

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

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!
  }
};

这会导致 main 出现问题:

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

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

【讨论】:

    【解决方案2】:

    调用访问私有数据成员的函数很好。 private 只是意味着你不能在类之外访问数据成员本身

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-12
        • 2013-08-30
        • 2020-09-04
        • 2020-09-01
        • 2018-05-11
        • 1970-01-01
        • 2016-05-08
        • 1970-01-01
        相关资源
        最近更新 更多