Private class member variables

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.