C++中protected的存取權限

來源:互聯網
上載者:User

標籤:簡單的   ring   protected   hive   base   end   key   process   strong   

轉載,釋然讀C++ Primer 心中疑惑: http://www.cnblogs.com/harlentan/archive/2011/03/05/2006444.html

關於C++中protected的存取權限的討論已經是一個很陳舊的話題了,陳舊到大家都不願意去討論,覺得他見到到吃飯睡覺那麼自然。

我再次讀《C++ Primer》的時候,其中關於protected 成員的描述是這樣的:

protected Members

The protected access label can be thought of as a blend of private and public :

  • Like private members, protected members are inaccessible to users of the class.
  • Like public members, the protected members are accessible to classes derived from this class.
  • In addition, protected has another important property:
    A derived object may access the protected members of its base class only through a derived object. The derived class has no special access to the protected members of base type objects.

在沒有繼承的情況下,protected跟private相同。在衍生類別的時候才出現分化。

上面那段英文前兩條都很好理解,基類對象不能訪問基類的protected成員,衍生類別中可以訪問基類的protected成員。也就是說private成員是不能被繼承的,只有public,protected的成員才可以被繼承。

就是最後一條有些迷惑人,衍生類別對象如果要訪問基類protected成員只有通過衍生類別對象,衍生類別不能訪問基類對象的protected成員。

請注意 drived class和drived object:衍生類別和衍生類別對象。第一點和第二點都是針對衍生類別來說的。

對於第三點總結一句話:只有在衍生類別中才可以通過衍生類別對象訪問基類的protected成員。

舉一個簡單的例子:

 

[cpp] view plain copy 
  1. #include <iostream>  
  2. using namespace std;  
  3. class Base  
  4. {  
  5. public:  
  6.     Base(){};  
  7.     virtual ~Base(){};  
  8. protected:  
  9.     int int_pro;  
  10. };  
  11. class A : public Base  
  12. {  
  13. public:  
  14.     A(){};  
  15.     A(int da){int_pro = da;}  
  16.     void Print(A &obj){obj.int_pro = 24;}  
  17.     void PrintPro(){cout << "The proteted data is " << int_pro <<endl;}  
  18. };  
  19. int main()  
  20. {  
  21.     A aObj;  
  22.     A aObj2(5);  
  23.     aObj2.PrintPro();  
  24.     aObj.Print(aObj2);  
  25.     aObj2.PrintPro();  
  26.       
  27.          //注釋1  
  28.          //aObj.int_pro = 8;  
  29. }  

 

編譯運行結果如下:

The protected data is 5

The protected data is 24

可見,在衍生類別內部直接存取protected成員和訪問衍生類別對象基類的protected成員都是可行的。

但是若果解開注釋1.就會編譯報錯。

很多書上都說有衍生類別的情況下protected的存取權限同public。這種說法是不對的,類內部直接存取沒什麼區別,但是訪問對象基類的protected成員只能是在該類的內部。

我這裡只列舉了只有一層繼承的情況,如果有多重繼承的情況,比如三層。那麼。中介層的類的內部還可以訪問第三層類對象的基類成員,但是不能訪問第三層類自己的protected的成員。

C++中protected的存取權限

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.