派生类访问基类的私有成员

派生类不能直接访问基类的私有成员,若要访问必须使用基类的接口,即通过其成员函数。实现方法有如下两种:


1.在基类的声明中增加保护成员,将基类中提供给派生类访问的私有成员定义为保护成员。
2.将需要访问基类私有成员的派生类成员函数声明为友元。


[cpp]
#include<iostream>
using namespace std;
class Base
{
      friend class Derived2;//friend
      int x;
      protected://protected
      int y;
};
class Derived1:Base//private继承 
{
public:
   /*    int getx()
       {
           return x;//不合法,访问基类的private成员
           }*/
       int gety()
       {
           return y;//合法,访问基类的protected成员 
           }
};
class Derived2:Base//private继承 
{
      public:
             int getx();
      };
int Derived2::getx()
{
    return x;//友员直接访问基类的私有成员 
    }
    
class Derived3:public Base//public继承 
{
      public:
          /*  
          int   getx()
             {
                   return x;//在这里还是不能访问,因为x是Base的private成员,只在Base里可以访问,在外面不可以被访问。
                   }
                   */
          int   gety()
             {
                   return y;
                   }
      };
int main()
{
    int i;
    Derived2 ob;//没有带参数的构造函数或成员函数初始化x,构造函数赋个随机值给x 
    i=ob.getx();
    cout<<i<<endl;
    Derived3 ob3;
    i=ob3.gety();
    cout<<i<<endl;
    system("pause");
    }

原文链接:http://www.2cto.com/kf/201209/152686.html

------------------------------------------------------------------------------------------------

转载于:https://www.cnblogs.com/followyourdream/p/3288522.html

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值