C++中public,protected,private的理解

來源:互聯網
上載者:User

標籤:div   prot   use   ted   友元   派生   oid   int()   pos   

 1 class BaseClass 2 { 3 public: 4     int public_int; 5 private: 6     int private_int; 7 protected: 8     int protected_int; 9 };10 11 class DerivedClass :public BaseClass {12 public:13     void UsePublicInt()14     {15         public_int = 1; //正確16     }17     void UserPrivateInt()18     {19         private_int = 1;//錯誤:成員 BaseClass::private_int不可訪問20     }21     void UserProtectedInt()22     {23         protected_int = 1; //正確 24     }25 };26 27 //protected 對ProtectedDerivedClass的衍生類別和使用者和友元函數產生影響,對ProtectedDerivedClass自身的成員函數無影響28 class ProtectedDerivedClass :protected BaseClass {29 public:30     void UsePublicInt()31     {32         public_int = 1; //正確 BaseClass::public_int是公有的33     }34     void UserPrivateInt()35     {36         private_int = 1;//錯誤:成員 BaseClass::private_int不可訪問37     }38     void UserProtectedInt()39     {40         protected_int = 1; //正確 41     }42 };43 44 int main()45 {46     BaseClass baseclass;47     baseclass.public_int; //正確48     baseclass.protected_int; //錯誤:成員 BaseClass::protected_int不可訪問49     baseclass.private_int; //錯誤:成員 BaseClass::private_int不可訪問50 51     DerivedClass derivedclass;52     derivedclass.public_int;   //正確53     derivedclass.protected_int; //錯誤:成員 BaseClass::protected_int不可訪問54     derivedclass.private_int; //錯誤:成員 BaseClass::private_int不可訪問 55 56     ProtectedDerivedClass protectedderivedclass;57     protectedderivedclass.public_int = 1;//錯誤:成員 BaseClass::public_int不可訪問 原因 ProtectedDerivedClass :protected DerivedClass,對ProtectedDerivedClass的使用者而言public_int是protectd,所以無法訪問58     protectedderivedclass.protected_int; //錯誤:成員 BaseClass::protected_int不可訪問59     protectedderivedclass.private_int; //錯誤:成員 BaseClass::private_int不可訪問 60 }

 

C++中public,protected,private的理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.