7. C ++ class and encapsulation concept, 7. c encapsulation Concept
Classes are generally divided into the following two parts:
- -ClassOfInternalImplementation
- -ClassOfExternalUsage
For example:
UserTo use a mobile phone, you only need to knowHow to Use.
WhileMobile phone developers, You need to consider the mobile phoneInternal implementationDetails.
Class Encapsulation
Not every member variable and member function of the class must be made public.
For example:
Girls do not want outsiders to know their weight and age
Boys don't want outsiders to know their height and salary
Some attributes are made public to the outside world.
For example:Name, education, nationality, etc.
Therefore, you can define the access level for the member variables and member functions in the class:
- -Public Public member,Allow member variables and member functions to be used inside and outside the class (public by default)
- -Private Private member, Can only be used inside the class
Scope of Class Members
The scope of all class members isOnly inside the class,External access failure
Member FunctionsYou can directlyAccess member variablesAndCall member functions
Class can be externalAccess public members through class variables
Class member'sScopeAndAccess LevelNo relationship
Refer to the following code:
# Include <stdio. h> int I = 1; // defines the global variable struct Test {private: int I; // defines the private member variable ipublic: int j; int getI () {I = 3; return I ;}; int main () {int I = 2; // defines the local variable I Test; test. j = 4; printf ("I = % d \ n", I); // I = 2; use the local variable printf (": I = % d \ n ",: I); //: I = 1; use the global variable // printf ("test. I = % d \ n ", test. i); // Error accessing the private member, Error printf ("test. j = % d \ n ", test. j); // test. j = 4 printf ("test. getI () = % d \ n ", test. getI ());
// Test. getI () = 3 access private member return 0 through public member ;}
Summary
Classes are generally dividedUsageAndInternal detailsTwo parts
Class encapsulation mechanism (Public/privateMake the usage and internal detailsPhase Separation