数据封装、数据抽象

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

 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值