Class member variables are privatized and accessed through read/write functions. This provides a consistent way (function) to access class member variables, while also providing a cheaper price for future changes. See the following Code :
1 Class A
2 {
3 Public :
4 A ( Int X): x (x)
5 {
6
7}
8 ~ A ()
9 {
10
11}
12 Public :
13 Int X;
14 } ;
15
16 Void F1 ( Const A & A1)
17 {
18Cout<A1.x<Endl;
19}
20 Void F2 ( Const A & A1)
21 {
22Cout<A1.x*A1.x<Endl;
23}
The F1 and F2 functions depend on the member variable X of Class A, that is, they directly read the value of the variable X of type. Assume that one day, the variable X is read after calculation, that is, the reading semantics of x changes (for example, the current reading semantics is x * X ), at this time, all code of member X Dependent on Type A must change...
For example, Program It is required to record all the places where variable X of type A is used. Similarly, we need to record all the places where variable X is used.
This is what we don't want to see. Why can't these jobs be transparent without changing the client code? The answer is yes. The following shows the modified implementation code: 1 Class A
2 {
3 Public :
4 A ( Int X): x (x)
5 {
6
7}
8 ~ A ()
9 {
10
11}
12 Public :
13 Int Getx () Const
14 {
15//Log
16ReturnX*X;
17}
18 Private :
19 Int X;
20 } ;
21
22 Void F1 ( Const A & A1)
23 {
24Cout<A1.getx ()<Endl;
25}
26 Void F2 ( Const A & A1)
27 {
28Cout<A1.getx ()*A1.getx ()<Endl;
29}
Summary: The member variables in the class should be private and accessed through the reader. Such encapsulated code has good scalability.