關於public,protected,private

來源:互聯網
上載者:User
  1. #include <iostream>
  2. using namespace std;
  3. class Base
  4. {
  5. public:
  6.  Base() { }
  7.  ~Base() { }
  8. public:
  9.  void FuncA() { cout << "FunA" << endl; }
  10. protected:
  11.  void FuncB() { cout << "FuncB" << endl; }
  12. private:
  13.  void FuncC() { cout << "FuncC" << endl; }
  14. };
  15. class CA : public Base
  16. {
  17. public:
  18.  CA() 
  19.  {
  20.   FuncA();
  21.   FuncB();
  22.   //FuncC(); // Error
  23.  }
  24.  ~CA() { }
  25. };
  26. class CB : protected Base
  27. {
  28. public:
  29.  CB()
  30.  {
  31.   FuncA();
  32.   FuncB();
  33.  // FuncC(); // Error
  34.  }
  35.  ~CB()
  36.  {}
  37. };
  38. class CC : private Base
  39. {
  40. public:
  41.  CC()
  42.  {
  43.   FuncA();
  44.   FuncB();
  45.   //FuncC(); // Error
  46.  }
  47.  ~CC()
  48.  {
  49.  }
  50. };
  51. int main( int argc, char *argv[] )
  52. {
  53.  CA a;
  54.  CB b;
  55.  CC c;
  56.  a.FuncA(); 
  57.  //a.FuncB(); // Error
  58.  //b.FuncA();  // Error
  59.  //b.FuncB();  // Error
  60.  //c.FuncA();   // Error
  61.  //c.FuncB();   // Error
  62.  return 0;
  63. }

關於public,protected,private
對於類執行個體(對象)的可見度:public可見,其他不可見
對於派生子類的可見度:public,protected可見,private不可見

用作派生方式時,如

public派生方式:
基類的public作為子類的public聲明,基類的protected作為子類的protected聲明,private當然還是private

protected派生方式:
基類的public和protected都作為子類的protected聲明,private還是private

private派生方式
基類的聲明都作為自己的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.