数据封装、数据抽象

数据封装是一种把数据和操作数据的函数捆绑在一起的机制,数据抽象是一种仅向用户暴露接口而把具体的实现细节隐藏起来的机制。把一个类定义为另一个类的友元类,会暴露实现细节,从而降低了封装性。理想的做法是尽可能地对外隐藏每个类的实现细节。

 1 #include <iostream>
 2 using namespace std;
 3 class Student
 4 {
 5 public:
 6     Student(double cMath, double cChiness, double cEnglish)     //形参不能和实参一样,否则会导致初始化不了
 7     {
 8         math = cMath;
 9         chiness = cChiness;
10         english = cEnglish;
11         sum = 0.0;
12     }
13     double GetInfo(string name)     //对外的接口,只需要知道函数的作用即可,不需要知道如何实现
14     {
15         GetAchievement(name);
16         return sum;
17     }
18     double GetInfo(string name, string pv)      //函数的重载
19     {
20         GetAchievement(name);
21         return sum/3;
22     }
23 private:
24     double math = 0;
25     double chiness = 0;
26     double english = 0;
27     double sum  = 0.0;
28     void GetAchievement(string name)    //函数用户不可见,数据抽象
29     {
30         if (name == "Tim")
31         {
32             sum = math + chiness + english;
33         }else {
34             sum = -1;
35         }
36     }
37 };
38 
39 int main()
40 {
41     Student std(97, 86, 85);
42     cout << std.GetInfo("Tim") << endl;
43     cout << std.GetInfo("Tim", "pv") << endl;;
44     system("pause");
45     return 0;
46 }

 结果为: 268 89.3333 

原文地址:https://www.cnblogs.com/xiaodangxiansheng/p/10999886.html