类的组合:

类的封装:


类封装的基本概念:

C++中的类的封装:

示例:
1 #include <stdio.h>
2
3 #include <stdio.h>
4
5 struct Biology
6 {
7 bool living;
8 };
9
10 struct Animal : Biology
11 {
12 bool movable;
13
14 void findFood()
15 {
16 }
17 };
18
19 struct Plant : Biology
20 {
21 bool growable;
22 };
23
24 struct Beast : Animal
25 {
26 void sleep()
27 {
28 }
29 };
30
31 struct Human : Animal
32 {
33 void sleep()
34 {
35 printf("I'm sleeping...\n");
36 }
37
38 void work()
39 {
40 printf("I'm working...\n");
41 }
42 };
43
44 struct Girl : Human
45 {
46 private:
47 int age;
48 int weight;
49 public:
50 void print()
51 {
52 age = 22;
53 weight = 48;
54
55 printf("I'm a girl, I'm %d years old.\n", age);
56 printf("My weight is %d kg.\n", weight);
57 }
58 };
59
60 struct Boy : Human
61 {
62 private:
63 int height;
64 int salary;
65 public:
66 int age;
67 int weight;
68
69 void print()
70 {
71 height = 175;
72 salary = 9000;
73
74 printf("I'm a boy, my height is %d cm.\n", height);
75 printf("My salary is %d RMB.\n", salary);
76 }
77 };
78
79 int main()
80 {
81 Girl g;
82 Boy b;
83
84 g.print();
85
86 b.age = 19;
87 b.weight = 120;
88 //b.height = 180;
89
90 b.print();
91
92 return 0;
93 }
88行是无法直接访问的。
print函数是定义在类的内部,可以访问成员的private对象。main函数是定义在类的外部,当然不可以直接访问类的private成员。
运行结果如下:

类成员的作用域:

类成员的作用域与类成员的访问级别不是一回事,它们之间没有关系。类成员的作用域在整个类的内部。而访问级别是对外部而言的。
示例程序:
1 #include <stdio.h>
2
3 int i = 1;
4
5 struct Test
6 {
7 private:
8 int i;
9
10 public:
11 int j;
12
13 int getI()
14 {
15 i = 3;
16
17 return i;
18 }
19 };
20
21 int main()
22 {
23 int i = 2;
24
25 Test test;
26
27 test.j = 4;
28
29 printf("i = %d\n", i); // i = 2;
30 printf("::i = %d\n", ::i); // ::i = 1;
31 // printf("test.i = %d\n", test.i); // Error
32 printf("test.j = %d\n", test.j); // test.j = 4
33 printf("test.getI() = %d\n", test.getI()); // test.getI() = 3
34
35 return 0;
36 }
第30行的::表示使用默认作用域中的i,默认作用域就是全局作用域。
运行结果如下:

小结:

来源:https://www.cnblogs.com/wanmeishenghuo/p/9563463.html