Inheritance Mode in C++
Inheritance Mode in C++
There are 3 kinds of inheritance mode: public private protected
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class B{ private: int b1; protected: int b2; public: int b3; }; class B1: private B{ }; class B2: protected B { }; class B3: public B { }; int main() { B b; b.b1; //no private b.b2; //no protected b.b3; //yes public B1 x; x.b1; //no private + private => private x.b2; //no protected + private => private x.b3; //no public + private => private B2 y; y.b1; //no private + protected => private y.b2; //no protected + protected =>protected y.b3; //no public + protected => protected B3 z; z.b1; //no private + public => private z.b2; //no protected + public =>protected z.b3; //yes public + public => public } |
we can change to each other between protected and public,but we can’t change private in base class to public or protected
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
class B{ private: int b1; protected: int b2; public: int b3; int b4; int b5; }; class B1: private B{ private: using B::b4; //ok public => private protected: using B::b3; //ok public => protected public: using B::b1; //error private => public using B::b2; //ok protected => public }; int main() { B1 x; x.b1; //error x.b2; //ok b2 has been changed to public x.b3; //error b3 has been changed to protected x.b4; //error b4 has been changed to private x.b5; //error public + private => private } |
分类: C/C++