访问控制
- 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;} };
- Protected members- Accessible to the members and friends of that class- Accessible to the members and friends of the **derived **class```cppclass Base{protected:int n;private:void foo1(Base& b){n++; // Okayb.n++; // Okay}};class Derived : public Base{void foo2(Base& b, Derived& d){n++; //Okaythis->n++; //Okay//b.n++; //Error.d.n++; //Okay}};
// 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
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
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
