派生類訪問基類的私有成員


派生類不能直接訪問基類的私有成員,若要訪問必須使用基類的接口,即通過其成員函數。實現方法有如下兩種:


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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM