访问控制

  • Public members
    • Accessible anywhere
  • Private members
    • Only accessible to the members and friends of that class ```cpp class Person { private: int n; // private member public: // this->n is accessible Person() : n(10) {} // other.n is accessible Person(const Person& other) : n(other.n) {} // this->n is accessible void set(int n) {this->n = n;} // this->n and other.n are accessible void set(const Person& other) {this->n = other.n;} };
  1. - Protected members
  2. - Accessible to the members and friends of that class
  3. - Accessible to the members and friends of the **derived **class
  4. ```cpp
  5. class Base
  6. {
  7. protected:
  8. int n;
  9. private:
  10. void foo1(Base& b)
  11. {
  12. n++; // Okay
  13. b.n++; // Okay
  14. }
  15. };
  16. class Derived : public Base
  17. {
  18. void foo2(Base& b, Derived& d)
  19. {
  20. n++; //Okay
  21. this->n++; //Okay
  22. //b.n++; //Error.
  23. d.n++; //Okay
  24. }
  25. };
// a non-member non-friend function 
void compare(Base& b, Derived& d)
{
    // b.n++; // Error
    // d.n++; // Error
}

Public Inheritance

  • Public members of the base class
    • Still be public in the derived class
    • Accessible anywhere
  • Protected members of the base class
    • Still be protected in the derived class
    • Accessible in the derived class only
  • Private members of the base class

    • Not accessible in the derived class

      Protected Inheritance

  • Public members and protected members of the base class

    • Be protected in the derived class
    • Accessible in the derived class only
  • Private members of the base class

    • Not accessible in the derived class

      Private Inheritance

  • Public members and protected members of the base class

    • Be private in the derived class
    • Accessible in the derived class only
  • Private members of the base class
    • Not accessible in the derived class