【问题标题】:Why sub class manage to access c++ private inheritance member? [duplicate]为什么子类设法访问 c++ 私有继承成员? [复制]
【发布时间】:2016-12-12 01:44:51
【问题描述】:

我的问题是为什么b.getmultiply(); 不会导致编译错误?

B 类是从 A 类私有继承的,xyA 类的成员。

class A {
    public:
    int x;
    int y;
    void set(int a, int b) { x = a; y =b;}
    };

class B : private A{
    public:
    int getmultiply (void){
        return x*y;}
};  

int main(void)
{
   B b;
    //b.set(3,4);     // this will cause compilation error
   cout << b.getmultiply();   // why this will not?? 
   return 0;
}

【问题讨论】:

    标签: c++ inheritance private


    【解决方案1】:

    当您从基类私有继承时,其公共成员将成为派生类的私有成员。这些成员是公共的,可以在派生类的成员函数内部访问(例如B.getmultiply()),但它们是私有的,不能被不是派生类朋友的外部代码(例如main())访问。

    【讨论】:

    • 谢谢,我终于明白了。
    【解决方案2】:

    当一个类从另一个类私有继承时,它仍然可以访问该类的(非私有)成员,就像在公共继承下一样。只有外部世界无法访问它们,因为它们在派生类的上下文中变为私有(事实上,外部世界甚至不知道派生是派生的:你不能引用B 的实例,例如带有 A 类型的指针)。

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      相关资源
      最近更新 更多