找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 3497|回复: 4

【C/C++面向对象方法实践:园丁游戏】

[复制链接]

85

主题

175

回帖

3990

积分

用户组: 超级版主

No. 418

UID
418
精华
14
威望
53 点
宅币
1974 个
贡献
1582 次
宅之契约
0 份
在线时间
252 小时
注册时间
2014-8-9
发表于 2015-10-17 20:54:38 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
开更老C的新作品:Practice With OO Method in C/C++: A Game Of Gardener(C/C++面向对象方法实践:园丁游戏)
作者:cyycoish。转载请注明作者出处,否则视为侵权。
这篇文章主要向大家介绍面向对象的实现方法。本文面向于那些对面向对象编程概念摸不着头脑的人们。接下来会使用C(注:C不是面向对象的语言),C++来加以说明。因为本人水平有限,如有错误之处欢迎指正批评共同进步。

第一篇:元始天尊

地球上生命的摇篮是大海,亿年前,蔚蓝的海水中出现的第一个生命的原型:细胞。
始祖鸟化石是人类已知最早的鸟类,虽然化石显示“始祖鸟”的牙齿还未完全退化,但是它已经拥有了羽毛。
面向对象的诞生同样充满了神话般的色彩,让我们通过C语言寻找面向对象诞生之初的影子。
下面来描述一下这个游戏:
A版本:
你现在是一个园丁,拥有一颗树苗。树苗生命值最大100。生命值为0则树苗死亡。
刚刚买回来,树苗生命值85,高度100cm。
以后每一天树苗因为生长生命值-15,而高度+10cm。
每天你可以执行4个操作其中的一个:
0.        退出游戏
1.        浇水
2.        修剪高度
3.        什么也不做
选择浇水,可以输入水量(以公升计算)。每浇水一升,树苗生命值+1 。如果生命值超过100,则进行倒扣(浇水过多植物寿命减少)。如果当天选择浇水,则树苗当天高度立即+6(树苗吸水增长)。
你的目标:使得树苗高度达到可以售卖的标准200cm。同时天数越短越好,树苗生命值越大越好。
注:超过200cm可以使用修剪功能减小树苗高度,但是剪切长度超过树苗高度,树苗即死亡。

以下是C语言描述:
  1. //代码1-1
  2. #include <stdio.h>

  3. #define HEIGHT_STANDARD 200 //标准高度

  4. void CutPlant(int* health, int* height, int iCuttOffHeightByCentiMeter) //剪切植物
  5. {
  6.         if (*height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  7.                 *height -= iCuttOffHeightByCentiMeter; //剪切
  8.         else
  9.                 *health = 0; //被剪死了
  10. }

  11. void WaterPlant(int* health, int* height, int iWaterQuantityByLitery) //浇水
  12. {
  13.         int Orghealth = *health; //记录浇水前的生命值
  14.         *health += iWaterQuantityByLitery; //生命值等于浇水水量
  15.         *height += 6; //每次浇水高度+6
  16.         if (*health > 100) //生命值大于100
  17.                 *health = Orghealth + 100 - *health; //生命值倒扣
  18.         if (*health < 0) //淹死了
  19.                 *health = 0;
  20.         printf("\thealth+ %d\n\tHeight+ 6\n", *health - Orghealth); //显示浇水后生命值以及高度的变化
  21. }

  22. int main(void)
  23. {
  24.         int iOption;
  25.         int iWQ;
  26.         int iCH;

  27.         int Day = 0; //天数
  28.         int Height = 100; //植物高度
  29.         int Health = 85;  //植物生命值

  30.         printf("Welcome!\nNow you have a sapling.\n");
  31.         printf("Begin your career as a gardener, and enjoy the game.\n");

  32.         while (Health > 0)
  33.         {
  34.                 Day++;
  35.                 printf("Days %d\n", Day);
  36.                 Health -= 15;
  37.                 printf("\tHealth -15.\n");
  38.                 if (Health > 20)
  39.                 {
  40.                         Height += 10;
  41.                         printf("\tHeight +10.\n");
  42.                 }
  43.                 printf("Reports:\n\tHeight: %d/200\n\tHealth: %d/100\n", Height, Health);
  44.                 if (Height == HEIGHT_STANDARD)
  45.                         break;
  46.                 if (Health <= 0)
  47.                         break;
  48.                 printf("[1]Water.[2]Cut.[0]Give it up.\n");
  49.                 scanf("%d", &iOption);
  50.                 switch (iOption)
  51.                 {
  52.                 case 1:
  53.                         printf("\tInput water quantity:");
  54.                         scanf("%d", &iWQ);
  55.                         WaterPlant(&Health, &Height, iWQ);
  56.                         break;
  57.                 case 2:
  58.                         printf("\tInput height to cut:");
  59.                         scanf("%d", &iCH);
  60.                         CutPlant(&Health, &Height, iCH);
  61.                         break;
  62.                 case 0:
  63.                         goto Lbl_Exit;
  64.                 default:
  65.                         printf("You did nothing?\n");
  66.                 }
  67.         }
  68. Lbl_Exit:
  69.         if (Health <= 0)
  70.                 printf("You bad gardener.The plant was die.\n");
  71.         else if (Height == HEIGHT_STANDARD)
  72.                 printf("%d Days,The plant was fit to sale for %d cm!\n", Day, HEIGHT_STANDARD);
  73.         else
  74.                 printf("Wont you keep going on it?\n");

  75.         return 0;
  76. }
复制代码

可以看见,为了满足面向过程程序设计的需要。以上代码将浇水和剪切两个动作从主过程中分离,抽象为两个函数。调用时以引用方式输入植物高度与生命值,分别判断修剪长度与浇水水量后,对高度及生命值做相应变化。
接下来对游戏规则进行修改:
B版本:
你现在是一个园丁,拥有两颗树苗。树苗生命值最大100。生命值为0则树苗死亡。
刚刚买回来,树苗生命值85,高度100cm。
以后每一天树苗因为生长生命值-15,而高度+10cm。
每天你可以对其中一棵树苗执行4个操作其中的一个:
0.        退出游戏
1.        浇水
2.        修剪高度
3.        什么也不做
选择浇水,可以输入水量(以公升计算)。每浇水一升,树苗生命值+1 。如果生命值超过100,则进行倒扣(浇水过多植物寿命减少)。如果当天选择浇水,则树苗当天高度立即+6(树苗吸水增长)。
你的目标:使得全部两颗树苗高度达到可以售卖的标准200cm。同时天数越短越好,树苗生命值越大越好。
注:超过200cm可以使用修剪功能减小树苗高度,但是剪切长度超过树苗高度,树苗即死亡。
其中一棵树苗高度达到200cm即可售卖。
分析:
先前针对A版本的游戏当中,树苗并未作为个体被抽象出来。因为只有一棵树苗,所以分别申请一个叫做Height的变量存放该树苗高度,Health变量存放生命值。现在树苗个数变为两个。我们是不是就应该这样子定义变量呢?int Height1;int Health1; int Height2;int Health2; 。那么如果是三颗树苗,4棵树苗,5棵树苗……。也许你可以这样子操作:int Height[N];int Health[N];。但是这样子不如将树苗作为“对象”抽象出来,定义一个结构体包含height与health属性来得方便些。于是我们有了结构体“Plant”其中有两个int类型变量:health和height。
此时,代码C语言描述如下:
  1. //代码1-2
  2. #include <stdio.h>
  3. #define HEIGHT_STANDARD 200 //植物标准高度

  4. struct Plant //结构体“植物”
  5. {
  6.         int height; //高度
  7.         int health; //生命值
  8. };

  9. struct Plant MyPlant[2];

  10. void InitAPlant(struct Plant* TargetPlant) //初始化函数
  11. {
  12.         TargetPlant->height = 100;
  13.         TargetPlant->health = 85;
  14. }

  15. void CutPlant(int* health, int* height, int iCuttOffHeightByCentiMeter) //剪切植物
  16. {
  17.         if (*height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  18.                 *height -= iCuttOffHeightByCentiMeter; //剪切
  19.         else
  20.                 *health = 0; //被剪死了
  21. }

  22. void WaterPlant(int* health, int* height, int iWaterQuantityByLitery) //浇水
  23. {
  24.         int Orghealth = *health; //记录浇水前的生命值
  25.         *health += iWaterQuantityByLitery; //生命值等于浇水水量
  26.         *height += 6; //每次浇水高度+6
  27.         if (*health > 100) //生命值大于100
  28.                 *health = Orghealth + 100 - *health; //生命值倒扣
  29.         if (*health < 0) //淹死了
  30.                 *health = 0;
  31.         printf("\thealth+ %d\n\tHeight+ 6\n", *health - Orghealth); //显示浇水后生命值以及高度的变化
  32. }

  33. int main()
  34. {
  35.         int iOption; //操作选择
  36.         int iWQ; //浇水水量
  37.         int iCH; //修剪长度

  38.         int Day = 0; //天数
  39.         InitAPlant(&MyPlant[0]); //初始化植物
  40.         InitAPlant(&MyPlant[1]); //初始化植物
  41.         int PlantsCounter = 2; //待完成养殖的植物个数
  42.         int CurrentPlantIndex; //当前被操作的植物索引

  43.         printf("Welcome!\nNow you have two saplings.\n");
  44.         printf("Begin your career as a gardener, and enjoy the game.\n");

  45.         while (PlantsCounter) //如果待完成养殖的植物个数为0则表示养殖任务完毕
  46.         {
  47.                 Day++;
  48.                 printf("Days %d\n", Day);
  49.                 MyPlant[0].health -= 15;
  50.                 MyPlant[1].health -= 15;
  51.                 if (MyPlant[0].health > 20) //如果植物生命在20以上,那么正常生长。
  52.                         MyPlant[0].height += 10;
  53.                 if (MyPlant[1].health > 20)
  54.                         MyPlant[1].height += 10;

  55.                 printf("Reports for plant 1:\n\tHeight: %d/200\n\tHealth: %d/100\n", MyPlant[0].height, MyPlant[0].health);
  56.                 printf("Reports for plant 2:\n\tHeight: %d/200\n\tHealth: %d/100\n", MyPlant[1].height, MyPlant[1].health);
  57.                 if (MyPlant[0].health <= 0) //植物死了一颗,游戏失败
  58.                         goto Lbl_Game_Over;
  59.                 if (MyPlant[1].health <= 0)
  60.                         goto Lbl_Game_Over;
  61.                 if (MyPlant[0].height == HEIGHT_STANDARD) //养成一颗
  62.                         PlantsCounter--; //待完成养殖的植物个数-1
  63.                 if (MyPlant[1].height == HEIGHT_STANDARD)
  64.                         PlantsCounter--;

  65.                 printf("Choose a plant to operate.[1] for 1st plant.[2] for 2nd plant.[AnyInputing] to pass any operating.\n");
  66.                 scanf("%d", &iOption); //选择一颗植物进行操作
  67.                 if (iOption != 1 && iOption != 2 || MyPlant[iOption - 1].height == HEIGHT_STANDARD) //没有选择任何一颗未完成之植物。因为C语言编译器对逻辑表达式的“短路计算”,MyPlant[iOption - 1]并不会越界。
  68.                         goto Lbl_Pass_Anyway;
  69.                 CurrentPlantIndex = iOption - 1; //修改索引
  70.                 printf("[1]Water.[2]Cut.[0]Give it up.\n");
  71.                 scanf("%d", &iOption);
  72.                 switch (iOption)
  73.                 {
  74.                 case 1:
  75.                         printf("\tInput water quantity:");
  76.                         scanf("%d", &iWQ);
  77.                         WaterPlant(&MyPlant[CurrentPlantIndex].health, &MyPlant[CurrentPlantIndex].height, iWQ);
  78.                         break;
  79.                 case 2:
  80.                         printf("\tInput height to cut:");
  81.                         scanf("%d", &iCH);
  82.                         CutPlant(&MyPlant[CurrentPlantIndex].health, &MyPlant[CurrentPlantIndex].height, iCH);
  83.                         break;
  84.                 case 3:
  85.                         goto Lbl_Exit;
  86.                 Lbl_Pass_Anyway:
  87.                 default:
  88.                         printf("You did nothing?\n");
  89.                 }
  90.         }
  91. Lbl_Exit:
  92.         if (MyPlant[0].health <= 0 || MyPlant[1].health <= 0)
  93.                 printf("You bad gardener.The plant was die.\n");
  94.         else if (MyPlant[0].height == HEIGHT_STANDARD && MyPlant[1].height == HEIGHT_STANDARD)
  95.                 printf("%d Days,All plants were fit to sale for %d cm!\n", Day, HEIGHT_STANDARD);
  96.         else
  97.                 printf("Wont you keep going on it?\n");
  98.         return 0;
  99. Lbl_Game_Over:
  100.         printf("One of your plants was die.");
  101.         return 0;
  102. }
复制代码

为了进一步说明声明结构体的重要性,我们来改进代码,使之支持达到“100”个植物!当然,随着植物数量增加,游戏难度随之增长。(那么因为时间关系,老C不在此代码上做可行性测试,以及详细的排bug处理,仅作为理论演示。)
改进后的C语言代码:
  1. //代码1-3
  2. #include <stdio.h>
  3. #define HEIGHT_STANDARD 200 //植物标准高度
  4. #define PLANTS 100 //100个植物

  5. struct Plant //结构体“植物”
  6. {
  7.         int height; //高度
  8.         int health; //生命值
  9. };

  10. struct Plant MyPlant[PLANTS];

  11. void InitAPlant(struct Plant* TargetPlant) //初始化函数
  12. {
  13.         TargetPlant->height = 100;
  14.         TargetPlant->health = 85;
  15. }

  16. void CutPlant(int* health, int* height, int iCuttOffHeightByCentiMeter) //剪切植物
  17. {
  18.         if (*height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  19.                 *height -= iCuttOffHeightByCentiMeter; //剪切
  20.         else
  21.                 *health = 0; //被剪死了
  22. }

  23. void WaterPlant(int* health, int* height, int iWaterQuantityByLitery) //浇水
  24. {
  25.         int Orghealth = *health; //记录浇水前的生命值
  26.         *health += iWaterQuantityByLitery; //生命值等于浇水水量
  27.         *height += 6; //每次浇水高度+6
  28.         if (*health > 100) //生命值大于100
  29.                 *health = Orghealth + 100 - *health; //生命值倒扣
  30.         if (*health < 0) //淹死了
  31.                 *health = 0;
  32.         printf("\thealth+ %d\n\tHeight+ 6\n", *health - Orghealth); //显示浇水后生命值以及高度的变化
  33. }

  34. int main()
  35. {
  36.         int i;
  37.         int iOption; //操作选择
  38.         int iWQ; //浇水水量
  39.         int iCH; //修剪长度

  40.         int Day = 0; //天数
  41.         for (i = 0; i < PLANTS; i++, InitAPlant(&MyPlant[i])); //初始化植物
  42.         int PlantsCounter = PLANTS; //待完成养殖的植物个数
  43.         int CurrentPlantIndex; //当前被操作的植物索引
  44.         int finishedIndex[PLANTS] = { 0 }; //记录完成索引

  45.         printf("Welcome!\nNow you have &d saplings.\n", PLANTS);
  46.         printf("Begin your career as a gardener, and enjoy the game.\n");

  47.         while (PlantsCounter) //如果待完成养殖的植物个数为0则表示养殖任务完毕
  48.         {
  49.                 Day++;
  50.                 printf("Days %d\n", Day);
  51.                 for (i = 0; i < PLANTS; i++)
  52.                 {
  53.                         MyPlant[i].health -= 15; //每天因为
  54.                         if (MyPlant[i].health > 20) //如果植物生命在20以上,那么正常生长。
  55.                                 MyPlant[i].height += 10;
  56.                         if (MyPlant[i].health <= 0) //植物死了一颗,游戏失败
  57.                                 goto Lbl_Game_Over;
  58.                         if (MyPlant[i].height == HEIGHT_STANDARD) //养成一颗
  59.                         {
  60.                                 PlantsCounter--; //待完成养殖的植物个数-1
  61.                                 finishedIndex[i] = 1;
  62.                         }
  63.                 }
  64.                 printf("Choose a plant to operate.Input a number range from 1 to %d\n", PLANTS);
  65.                 printf("Here are unfinished plants which you can choose.:\n");
  66.                 for (i = 0; i < PLANTS; i++, (!finishedIndex[i]) ? printf("%d ", i) : 1); //打印未完成养殖的植物
  67.                 printf("\nIf your choice out of the above-mentioned, Current operating will be passed.PLEASE TREAT IT SERIOUSLY.\n");
  68.                 scanf("%d", &iOption); //选择一颗植物进行操作
  69.                 for (i = 0; i < PLANTS; i++, CurrentPlantIndex = (!finishedIndex[i]) && iOption - 1 == i ? i : -1); //选择一颗符合上述条件的植物
  70.                 if (CurrentPlantIndex == -1)
  71.                         goto Lbl_Pass_Anyway;
  72.                 printf("[1]Water.[2]Cut.[0]Give it up.\n");
  73.                 scanf("%d", &iOption);
  74.                 switch (iOption)
  75.                 {
  76.                 case 1:
  77.                         printf("\tInput water quantity:");
  78.                         scanf("%d", &iWQ);
  79.                         WaterPlant(&MyPlant[CurrentPlantIndex].health, &MyPlant[CurrentPlantIndex].height, iWQ);
  80.                         break;
  81.                 case 2:
  82.                         printf("\tInput height to cut:");
  83.                         scanf("%d", &iCH);
  84.                         CutPlant(&MyPlant[CurrentPlantIndex].health, &MyPlant[CurrentPlantIndex].height, iCH);
  85.                         break;
  86.                 case 3:
  87.                         goto Lbl_Exit;
  88.                 Lbl_Pass_Anyway:
  89.                 default:
  90.                         printf("You did nothing?\n");
  91.                 }
  92.         }
  93.         printf("%d Days,All plants were fit to sale for %d cm!\n", Day, HEIGHT_STANDARD);
  94.         return 0;
  95. Lbl_Exit:
  96.         printf("Wont you keep going on it?\n");
  97.         return 0;
  98. Lbl_Game_Over:
  99.         printf("One of your plants was die.");
  100.         return 0;
  101. }
复制代码

这时候大家有没有觉得瞬间,大量的物体被以一种更“集成化”的方式,简约地处理掉了。
至此我们已经知道类的雏形,是的,他就是:结构体(structure)
回复

使用道具 举报

85

主题

175

回帖

3990

积分

用户组: 超级版主

No. 418

UID
418
精华
14
威望
53 点
宅币
1974 个
贡献
1582 次
宅之契约
0 份
在线时间
252 小时
注册时间
2014-8-9
 楼主| 发表于 2015-10-17 21:15:33 | 显示全部楼层
第二篇:海纳百川,包罗万象

有古训:有容乃大。一个集大成者的计算机语言必然可以使得使用它的人来描述任何东西。
不可否认,OOP(即面向对象编程)是计算机语言的革命。打赢这一场翻身仗OOP需要经过包罗万象的考验。
我们继续以“园丁游戏A版本”为蓝本修改游戏规则:
C版本:
你现在是一个园丁,拥有两颗树苗。一颗苹果树,一颗橘子树。树苗生命值最大100。生命值为0则树苗死亡。
刚刚买回来,树苗生命值85,高度100cm,都没有结果子。
以后每一天树苗因为生长生命值-15,而高度+10cm。
苹果树在生命值大于等于30的情况下,每天结一颗果子。
橘子树在生命值大于等于60的情况下,每天结一颗果子。

两颗果树每一颗果子每一天消耗生命值2
每天你可以执行4个操作其中的一个:
0.        退出游戏
1.        浇水
2.        修剪高度
3.        摘果子
4.        什么也不做
选择浇水,可以输入水量(以公升计算)。每浇水一升,树苗生命值+1 。如果生命值超过100,则进行倒扣(浇水过多植物寿命减少)。如果当天选择浇水,则树苗当天高度立即+6(树苗吸水增长)。
选择摘果子,可以输入摘果数量,该数量不能大于结果数。
你的目标:使得树苗高度达到可以售卖的标准200cm。同时天数越短越好。达到200cm后的果树:苹果与橘子单个售价均为$1, 卖果子所得的钱将作为你的额外收入。收入越多越好。
注:超过200cm可以使用修剪功能减小树苗高度,但是剪切长度超过树苗高度,树苗即死亡。
这是第一个版本并不完善的C代码:
  1. //代码2-1
  2. #include <stdio.h>
  3. #define HEIGHT_STANDARD 200 //植物标准高度

  4. struct Plant //结构体“植物”
  5. {
  6.         int height; //高度
  7.         int health; //生命值
  8.         int apple;  //苹果个数
  9.         int orange; //橘子个数
  10. };

  11. struct Plant AppleTree;  //苹果树
  12. struct Plant OrangeTree; //橘子树

  13. void InitAPlant(struct Plant* TargetPlant) //初始化函数
  14. {
  15.         TargetPlant->height = 100;
  16.         TargetPlant->health = 85;
  17.         TargetPlant->apple = 0;
  18.         TargetPlant->orange = 0;
  19. }

  20. void CutPlant(int* health, int* height, int iCuttOffHeightByCentiMeter) //剪切植物
  21. {
  22.         if (*height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  23.                 *height -= iCuttOffHeightByCentiMeter; //剪切
  24.         else
  25.                 *health = 0; //被剪死了
  26. }

  27. void WaterPlant(int* health, int* height, int iWaterQuantityByLitery) //浇水
  28. {
  29.         int Orghealth = *health; //记录浇水前的生命值
  30.         *health += iWaterQuantityByLitery; //生命值等于浇水水量
  31.         *height += 6; //每次浇水高度+6
  32.         if (*health > 100) //生命值大于100
  33.                 *health = Orghealth + 100 - *health; //生命值倒扣
  34.         if (*health < 0) //淹死了
  35.                 *health = 0;
  36.         printf("\thealth+ %d\n\tHeight+ 6\n", *health - Orghealth); //显示浇水后生命值以及高度的变化
  37. }

  38. void PickFruit(struct Plant* fruitTree, int howManyFruits)
  39. {
  40.         int Apple = fruitTree->apple;   //苹果数
  41.         int Orange = fruitTree->orange; //橘子数
  42.         //摘果
  43.         if (Apple > 0 && Apple - howManyFruits >= 0)
  44.                 fruitTree->apple -= howManyFruits;
  45.         if (Orange > 0 && Orange - howManyFruits >= 0)
  46.                 fruitTree->orange -= howManyFruits;
  47. }

  48. int main()
  49. {
  50.         int i;
  51.         int iOption; //操作选择
  52.         int iWQ; //浇水水量
  53.         int iCH; //修剪长度
  54.         int iFT; //摘果个数

  55.         int Day = 0; //天数

  56.         InitAPlant(&AppleTree);
  57.         InitAPlant(&OrangeTree);

  58.         struct Plant* TargetPlant;

  59.         printf("Welcome!\nNow you have double saplings.\n");
  60.         printf("Begin your career as a gardener, and enjoy the game.\n");

  61.         while (1)
  62.         {
  63.                 Day++;
  64.                 printf("Days %d\n", Day);
  65.                 AppleTree.health -= 15 + AppleTree.apple * 2;
  66.                 OrangeTree.health -= 15 + OrangeTree.orange * 2;
  67.                 printf("\tHealth -15.\n");
  68.                 if (AppleTree.health > 20)
  69.                         AppleTree.height += 10;
  70.                 if (OrangeTree.health > 20)
  71.                         OrangeTree.height += 10;
  72.                 if (AppleTree.health >= 30)
  73.                         AppleTree.apple++;
  74.                 if (OrangeTree.health >= 60)
  75.                         OrangeTree.orange++;
  76.                 printf("Reports for apple tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", AppleTree.height, AppleTree.health, AppleTree.apple);
  77.                 printf("Reports for orange tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", OrangeTree.height, OrangeTree.health, OrangeTree.orange);

  78.                 if (AppleTree.health <= 0 || OrangeTree.health <= 0)
  79.                         goto Lbl_Game_Over;

  80.                 printf("Choose a plant to operate.[0] for apple tree,[Any inputing] for orange tree.\n");
  81.                 scanf("%d", &iOption);
  82.                 if (!iOption && AppleTree.height != HEIGHT_STANDARD)
  83.                         TargetPlant = &AppleTree;
  84.                 else
  85.                         TargetPlant = &OrangeTree;

  86.                 printf("[1]Water.[2]Cut.[3]Pick Fruits.[0]Give it up.\n");
  87.                 scanf("%d", &iOption);
  88.                 switch (iOption)
  89.                 {
  90.                 case 1:
  91.                         printf("\tInput water quantity:");
  92.                         scanf("%d", &iWQ);
  93.                         WaterPlant(&TargetPlant->health, &TargetPlant->height, iWQ);
  94.                         break;
  95.                 case 2:
  96.                         printf("\tInput height to cut:");
  97.                         scanf("%d", &iCH);
  98.                         CutPlant(&TargetPlant->health, &TargetPlant->height, iCH);
  99.                         break;
  100.                 case 3:
  101.                         printf("\tInput quantity to pick up:");
  102.                         scanf("%d", &iFT);
  103.                         PickFruit(TargetPlant, iFT);
  104.                         break;
  105.                 case 0:
  106.                         goto Lbl_Exit;
  107.                 Lbl_Pass_Anyway:
  108.                 default:
  109.                         printf("You did nothing?\n");
  110.                 }
  111.         }
  112.         printf("%d Days,All plants were fit to sale! Any you got $%d for pocket money!\n", Day, AppleTree.apple + OrangeTree.orange);
  113.         return 0;
  114. Lbl_Exit:
  115.         printf("Wont you keep going on it?\n");
  116.         return 0;
  117. Lbl_Game_Over:
  118.         printf("One of your plants was die.");
  119.         return 0;
  120. }
复制代码

现在,我们要对以上代码进行重构,以便达到更好的封装,使代码能被充分“物尽其用”。将植物本身的特性尽可能地赋予植物内部。我们所做的第二步是要简化“上帝”的工作。尽量缩减主函数。
  1. //代码2-2
  2. #include <stdio.h>
  3. #define HEIGHT_STANDARD 200 //植物标准高度
  4. #define THIS TargetPlant

  5. struct Plant //结构体“植物”
  6. {
  7.         int height; //高度
  8.         int health; //生命值
  9.         int apple;  //苹果个数
  10.         int orange; //橘子个数
  11.         void(*Cut)(struct Plant* TargetPlant, int iCuttOffHeightByMillimeter); //修剪植物
  12.         void(*Water)(struct Plant* TargetPlant, int iWaterQuantityByLitery);   //浇水
  13.         void(*PickFruits)(struct Plant* TargetPlant, int howManyFruits);       //摘果子
  14. };

  15. struct Plant AppleTree;  //苹果树
  16. struct Plant OrangeTree; //橘子树

  17. void CutPlant(struct Plant* TargetPlant, int iCuttOffHeightByCentiMeter) //剪切植物
  18. {
  19.         if (TargetPlant->height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  20.                 TargetPlant->height -= iCuttOffHeightByCentiMeter; //剪切
  21.         else
  22.                 TargetPlant->health = 0; //被剪死了
  23. }

  24. void WaterPlant(struct Plant* TargetPlant, int iWaterQuantityByLitery) //浇水
  25. {
  26.         int Orghealth = TargetPlant->health; //记录浇水前的生命值
  27.         TargetPlant->health += iWaterQuantityByLitery; //生命值等于浇水水量
  28.         TargetPlant->health += 6; //每次浇水高度+6
  29.         if (TargetPlant->health > 100) //生命值大于100
  30.                 TargetPlant->health = Orghealth + 100 - TargetPlant->health; //生命值倒扣
  31.         if (TargetPlant->health < 0) //淹死了
  32.                 TargetPlant->health = 0;
  33.         printf("\thealth+ %d\n\tHeight+ 6\n", TargetPlant->health - Orghealth); //显示浇水后生命值以及高度的变化
  34. }

  35. void PickFruit(struct Plant* fruitTree, int howManyFruits)
  36. {
  37.         int Apple = fruitTree->apple;   //苹果数
  38.         int Orange = fruitTree->orange; //橘子数
  39.         //摘果
  40.         if (Apple > 0 && Apple - howManyFruits >= 0)
  41.                 fruitTree->apple -= howManyFruits;
  42.         if (Orange > 0 && Orange - howManyFruits >= 0)
  43.                 fruitTree->orange -= howManyFruits;
  44. }

  45. void HangARealDay(void)
  46. {
  47.         AppleTree.health -= 15 + AppleTree.apple * 2;
  48.         OrangeTree.health -= 15 + OrangeTree.orange * 2;
  49.         printf("\tHealth -15.\n");
  50.         if (AppleTree.health > 20)
  51.                 AppleTree.height += 10;
  52.         if (OrangeTree.health > 20)
  53.                 OrangeTree.height += 10;
  54.         if (AppleTree.health >= 30)
  55.                 AppleTree.apple++;
  56.         if (OrangeTree.health >= 60)
  57.                 OrangeTree.orange++;
  58.         printf("Reports for apple tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", AppleTree.height, AppleTree.health, AppleTree.apple);
  59.         printf("Reports for orange tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", OrangeTree.height, OrangeTree.health, OrangeTree.orange);
  60. }

  61. void InitAPlant(struct Plant* TargetPlant) //初始化函数
  62. {
  63.         TargetPlant->height = 100;
  64.         TargetPlant->health = 85;
  65.         TargetPlant->apple = 0;
  66.         TargetPlant->orange = 0;
  67.         TargetPlant->Cut = CutPlant;
  68.         TargetPlant->Water = WaterPlant;
  69.         TargetPlant->PickFruits = PickFruit;
  70. }

  71. int main()
  72. {
  73.         int iOption; //操作选择
  74.         int subOption;

  75.         int Day = 0; //天数

  76.         InitAPlant(&AppleTree);
  77.         InitAPlant(&OrangeTree);

  78.         struct Plant* TargetPlant;

  79.         printf("Welcome!\nNow you have double saplings.\n");
  80.         printf("Begin your career as a gardener, and enjoy the game.\n");

  81.         while (1)
  82.         {
  83.                 Day++;
  84.                 printf("Days %d\n", Day);
  85.                 HangARealDay(); //Hang A Real Day is HARD.

  86.                 if (AppleTree.health <= 0 || OrangeTree.health <= 0)
  87.                         goto Lbl_Game_Over;

  88.                 printf("Choose a plant to operate.[0] for apple tree,[1] for orange tree.\n");
  89.                 scanf("%d", &iOption);
  90.                 if (!iOption && AppleTree.height != HEIGHT_STANDARD)
  91.                         TargetPlant = &AppleTree;
  92.                 else if (iOption == 1 && OrangeTree.height != HEIGHT_STANDARD)
  93.                         TargetPlant = &OrangeTree;
  94.                 else
  95.                         goto Lbl_Pass_Anyway;

  96.                 printf("[1]Water.[2]Cut.[3]Pick Fruits.[0]Give it up.\n");
  97.                 scanf("%d", &iOption);
  98.                 switch (iOption)
  99.                 {
  100.                 case 1:
  101.                         printf("\tInput water quantity:");
  102.                         scanf("%d", &subOption);
  103.                         TargetPlant->Water(THIS, subOption); //THIS就代表TargetPlant
  104.                         break;
  105.                 case 2:
  106.                         printf("\tInput height to cut:");
  107.                         scanf("%d", &subOption);
  108.                         TargetPlant->Cut(THIS, subOption); //THIS就代表TargetPlant
  109.                         break;
  110.                 case 3:
  111.                         printf("\tInput quantity to pick up:");
  112.                         scanf("%d", &subOption);
  113.                         TargetPlant->PickFruits(THIS, subOption); //THIS就代表TargetPlant
  114.                         break;
  115.                 case 0:
  116.                         goto Lbl_Exit;
  117.                 Lbl_Pass_Anyway:
  118.                 default:
  119.                         printf("You did nothing?\n");
  120.                 }
  121.         }
  122.         printf("%d Days,All plants were fit to sale! Any you got $%d for pocket money!\n", Day, AppleTree.apple + OrangeTree.orange);
  123.         return 0;
  124. Lbl_Exit:
  125.         printf("Wont you keep going on it?\n");
  126.         return 0;
  127. Lbl_Game_Over:
  128.         printf("One of your plants was die.");
  129.         return 0;
  130. }
复制代码

消减后的主函数代码67行,比原先减少13行。当然,这是分离出HangARealDay函数带来的结果。但是在加入了THIS宏后,对植物进行的操作变成调用了植物结构体内的函数指针,使得代码可以被更好理解。当然,结构体内所有的成员(包括变量和指向函数的指针)都要在使用之前被InitAPlant函数初始化。
至此,我们发现,一个重大的转变就是将函数放在了结构体内,而不是HangARealDay函数缩减的仅有的13行代码。原先零散的函数瞬间被“收集”起来了。如果将结构体和其中函数指针指向的函数写入另外一个C文件,那么,只要提供函数调用说明,我们就可以随心所欲设置HangARealDay中的游戏规则。当然,修改植物本身的属性也变得极为方便——只要修改植物结构体中函数指针指向的函数内部内容即可。
结构体变得丰富起来了。不再是仅有的变量表示的事物属性,甚至是一个事物可以执行的动作,或者受外界刺激做出的反应。我们不仅仅可以用C语言计算一个“生物”局限的,微观的状态,我们可以造就模拟一整条“食物链”。
In the beginning I was not the best.
And the world was also not the best.
But I still know that I am who I am.
Because I think that it is good.
I have been working hard.
I have been keeping growth with the world.
And it was so.
回复 赞! 靠!

使用道具 举报

85

主题

175

回帖

3990

积分

用户组: 超级版主

No. 418

UID
418
精华
14
威望
53 点
宅币
1974 个
贡献
1582 次
宅之契约
0 份
在线时间
252 小时
注册时间
2014-8-9
 楼主| 发表于 2015-10-17 21:25:04 | 显示全部楼层
第三篇:革命日

夏末海边,天气闷热。
忽然间,铅色黑云,风高浪急。
岸边海鸟焦急地盘旋,一场暴风雨前不是宁静的。每一道闪电都点亮天空,随之而来的是雷声的呐喊:迎接秋日的到来吧!换季的时间到了,我们要革命!
解除软件开发人员的枷锁,C已无力胜任。革命家般的C++之父从头撤尾改造了C。
我们现在使用C++第一遍重写版本C的园丁游戏。
C++代码:
  1. //代码3-1
  2. #include <stdio.h>
  3. const int HEIGHT_STANDARD = 200; //植物标准高度

  4. class Plant//植物类
  5. {
  6. public: //公开类中所有成员
  7.         int height = 100;
  8.         int health = 85;
  9.         int apple = 0;
  10.         int orange = 0;
  11.         void Cut(int iCuttOffHeightByCentiMeter);  //剪切植物
  12.         void Water(int iWaterQuantityByLitery);    //浇水
  13.         void PickFruit(int howManyFruits);         //摘果子
  14. };

  15. void Plant::Cut(int iCuttOffHeightByCentiMeter) //成员函数
  16. {
  17.         if (height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  18.                 height -= iCuttOffHeightByCentiMeter; //剪切
  19.         else
  20.                 health = 0; //被剪死了
  21. }

  22. void Plant::Water(int iWaterQuantityByLitery) //成员函数
  23. {
  24.         int Orghealth = health; //记录浇水前的生命值
  25.         health += iWaterQuantityByLitery; //生命值等于浇水水量
  26.         health += 6; //每次浇水高度+6
  27.         if (health > 100) //生命值大于100
  28.                 health = Orghealth + 100 - health; //生命值倒扣
  29.         if (health < 0) //淹死了
  30.                 health = 0;
  31.         printf("\thealth+ %d\n\tHeight+ 6\n", health - Orghealth); //显示浇水后生命值以及高度的变化
  32. }

  33. void Plant::PickFruit(int howManyFruits) //成员函数
  34. {
  35.         int Apple = apple;   //苹果数
  36.         int Orange = orange; //橘子数
  37.                                                  //摘果
  38.         if (Apple > 0 && Apple - howManyFruits >= 0)
  39.                 apple -= howManyFruits;
  40.         if (Orange > 0 && Orange - howManyFruits >= 0)
  41.                 orange -= howManyFruits;
  42. }

  43. void HangARealDay(Plant* AppleTree, Plant* OrangeTree) //全局函数
  44. {
  45.         AppleTree->health -= 15 + AppleTree->apple * 2;
  46.         OrangeTree->health -= 15 + OrangeTree->orange * 2;
  47.         printf("\tHealth -15\n");
  48.         if (AppleTree->health > 20)
  49.                 AppleTree->height += 10;
  50.         if (OrangeTree->health > 20)
  51.                 OrangeTree->height += 10;
  52.         if (AppleTree->health >= 30)
  53.                 AppleTree->apple++;
  54.         if (OrangeTree->health >= 60)
  55.                 OrangeTree->orange++;
  56.         printf("Reports for apple tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", AppleTree->height, AppleTree->health, AppleTree->apple);
  57.         printf("Reports for orange tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", OrangeTree->height, OrangeTree->health, OrangeTree->orange);
  58. }

  59. int main()
  60. {
  61.         int iOption; //操作选择
  62.         int subOption;

  63.         int Day = 0; //天数

  64.         Plant* AppleTree = new Plant;  //以Plant为模板,建造一棵苹果树
  65.         Plant* OrangeTree = new Plant; //以Plant为模板,建造一棵橘子树
  66.         Plant* TargetPlant;

  67.         printf("Welcome!\nNow you have double saplings.\n");
  68.         printf("Begin your career as a gardener, and enjoy the game.\n");

  69.         while (1)
  70.         {
  71.                 Day++;
  72.                 printf("Days %d\n", Day);
  73.                 HangARealDay(AppleTree, OrangeTree);

  74.                 if (AppleTree->health <= 0 || OrangeTree->health <= 0)
  75.                         goto Lbl_Game_Over;
  76.                 printf("Choose a plant to operate.[0] for apple tree,[1] for orange tree.\n");
  77.                 scanf("%d", &iOption);
  78.                 if (!iOption && AppleTree->height != HEIGHT_STANDARD)
  79.                         TargetPlant = AppleTree;
  80.                 else if (iOption == 1 && OrangeTree->height != HEIGHT_STANDARD)
  81.                         TargetPlant = OrangeTree;
  82.                 else
  83.                         goto Lbl_Pass_Anyway;

  84.                 printf("[1]Water.[2]Cut.[3]Pick Fruits.[0]Give it up.\n");
  85.                 scanf("%d", &iOption);
  86.                 switch (iOption)
  87.                 {
  88.                 case 1:
  89.                         printf("\tInput water quantity:");
  90.                         scanf("%d", &subOption);
  91.                         TargetPlant->Water(subOption); //省略THIS
  92.                         break;
  93.                 case 2:
  94.                         printf("\tInput height to cut:");
  95.                         scanf("%d", &subOption);
  96.                         TargetPlant->Cut(subOption); //省略THIS
  97.                         break;
  98.                 case 3:
  99.                         printf("\tInput quantity to pick up:");
  100.                         scanf("%d", &subOption);
  101.                         TargetPlant->PickFruit(subOption); //省略THIS
  102.                         break;
  103.                 case 0:
  104.                         goto Lbl_Exit;
  105.                 Lbl_Pass_Anyway:
  106.                 default:
  107.                         printf("You have done nothing?\n");
  108.                 }
  109.         }
  110.         printf("%d Days,All plants were fit to sale! Any you got $%d for pocket money!\n", Day, AppleTree->apple + OrangeTree->orange);
  111.         return 0;
  112. Lbl_Exit:
  113.         printf("Wont you keep going on it?\n");
  114.         return 0;
  115. Lbl_Game_Over:
  116.         printf("One of your plants was die.");
  117.         return 0;
  118. }
复制代码

如果大家仔细阅读并且思考了本文上述全部C代码,不难看出:class Plant(植物类)其实是一个结构体,然而,这个结构体内的变量能被直接初始化。类中声明的函数,就是前面C结构体中的函数指针。具体的函数实现就是下面的成员函数。“::”符号是访问限定符,int Plant::XXX()表示int XXX函数属于类Plant。成员函数内部可以直接使用所在类内部的变量而无须使用“THIS”指针。
创建一个以这个类为数据类型的变量使用语句:ClassName* var = new ClassName;,或者ClassName var;。这个过程被称作为“类的实例化”。var就是该类实例化出来的一个对象。
接下来大家需要搞懂以下几个概念:内联成员函数、this指针、构造函数、析构函数。
内联成员函数:
在C的结构体中,函数指针要在结构体外部做实现,那么在C++中,可以在类中直接实现该函数。这个函数被称为“内联成员函数”请看:
  1. //代码3-2
  2. class Plant//植物类
  3. {
  4. public: //公开类中所有成员
  5.         int height = 100;
  6.         int health = 85;
  7.         int apple = 0;
  8.         int orange = 0;
  9.         void Cut(int iCuttOffHeightByCentiMeter)       //剪切植物
  10.         {
  11.                 if (height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  12.                         height -= iCuttOffHeightByCentiMeter; //剪切
  13.                 else
  14.                         health = 0; //被剪死了
  15.         }
  16.         inline void Water(int iWaterQuantityByLitery); //浇水
  17.         void PickFruit(int howManyFruits);             //摘果子
  18. };

  19. void Plant::Water(int iWaterQuantityByLitery) //成员函数
  20. {
  21.         int Orghealth = health; //记录浇水前的生命值
  22.         health += iWaterQuantityByLitery; //生命值等于浇水水量
  23.         health += 6; //每次浇水高度+6
  24.         if (health > 100) //生命值大于100
  25.                 health = Orghealth + 100 - health; //生命值倒扣
  26.         if (health < 0) //淹死了
  27.                 health = 0;
  28.         printf("\thealth+ %d\n\tHeight+ 6\n", health - Orghealth); //显示浇水后生命值以及高度的变化
  29. }

  30. void Plant::PickFruit(int howManyFruits) //成员函数
  31. {
  32.         int Apple = apple;   //苹果数
  33.         int Orange = orange; //橘子数
  34.                                                  //摘果
  35.         if (Apple > 0 && Apple - howManyFruits >= 0)
  36.                 apple -= howManyFruits;
  37.         if (Orange > 0 && Orange - howManyFruits >= 0)
  38.                 orange -= howManyFruits;
  39. }
复制代码

那么在类Plant中,Cut函数为内联成员函数。而函数名称前加上inline关键字,函数实现在类以外,编译器也会自动视为“内联成员函数”。显然,函数PickFruit既没有加inline关键字在类中的声明之前,也没有在类中实现该函数。所以PickFruit不是“内联成员函数”。内联成员函数的出现是为了增加执行效率,其缺点是增加了类的体积。显然,将一些体积小的,执行次数多的函数内联是一个两全其美的好办法。
下面来说一说“this指针”:
还记得在C中我们如何定义Cut函数的吗?我找来了它的定义,在12页上面的代码:
void CutPlant(struct Plant* TargetPlant, int iCuttOffHeightByCentiMeter);
然后位于代码第三行处有一个THIS宏:#define THIS TargetPlant 。当我们使用Cut函数时是这样子调用的:TargetPlant->Cut(THIS, subOption); //THIS就代表TargetPlant 而在C++中我们调用Cut函数的时候:TargetPlant->Cut(subOption); //省略THIS 。
至此我们不难猜想得到,C++中,this指针用来访问“成员函数所在类中的成员变量”。这样说还不对!请看:
  1. //代码3-3
  2. #include <iostream>
  3. using namespace std;

  4. class MyClass
  5. {
  6. public:
  7.         char word[100] = {"Hello nice to meet you!\n"};
  8.         void SayHelloA()
  9.         {
  10.                 cout << "Hello glad to see you!" << endl;
  11.         }
  12.         void SayHelloB()
  13.         {
  14.                 cout << word;
  15.         }
  16. };

  17. int main()
  18. {
  19.         MyClass* objHelloA = new MyClass;
  20.         MyClass* objHelloB = NULL;
  21.         objHelloA->SayHelloA();
  22.         objHelloA->SayHelloB();

  23.         objHelloB->SayHelloA(); //请将断点下于此处
  24.         objHelloB->SayHelloB(); //运行出错

  25.         return 0;
  26. }
复制代码

在以上代码中objHelloA->SayHelloA();objHelloA->SayHelloB();能被正常执行并不会被觉得奇怪,但是大家有没有想过objHelloB->SayHelloA();为什么也能被执行?而objHelloB->SayHelloB();立即报错?解释是:类是一个结构体,其中的成员函数都是函数指针。objHelloB指向了一个空的内存地址,然而在申请“结构体”类时,内部所有函数指针已经被指向指定函数。所以,通过类的实例可以调用成员函数,却不能访问成员变量。
  1. //代码3-4
  2. #include <iostream>
  3. using namespace std;

  4. class MyClass
  5. {
  6. public:
  7.         int counter = 0;
  8.         void Increase();
  9. };

  10. void MyClass::Increase()
  11. {
  12.         this->counter++;
  13. }

  14. int main()
  15. {
  16.         MyClass* objA = new MyClass;
  17.         MyClass* objB = new MyClass;
  18.         objA->Increase();
  19.         cout << objB->counter << endl;
  20.         return 0;
  21. }
复制代码

在以上代码中,如果this指针可以通知类这个“模子”本身的话,那么所有由这个模子构造出来的实例的counter变量值都应该+1,输出结果应为:
1
1
而实际上输出结果为:
1
0
所以this指针访问该实例构造出来的,属于该实例“自己”的那个类的内存中的成员变量counter。简而言之,objA在new的时候new出来一个:int counter = 0; 、一个void(*Increase)(void); ,objB在new的时候“又”new出来一个int counter = 0; 、一个void(*Increase)(void); 。如果再new一个objC,那么内存中再多一组int counter = 0; 、void(*Increase)(void); 。此时虽然三个obj都有counter,但是objC中的Increase函数只访问objC内存中的counter。
为了说明构造函数,我们需要改进“园丁游戏C版本”。我们叫改进过的C版本为“园丁游戏C-2”
C-2版本:
你现在是一个园丁,拥有两颗树苗。一颗苹果树,一颗橘子树。树苗生命值最大100。生命值为0则树苗死亡。
刚刚买回来,苹果树苗生命值85,高度100cm,没有结果子。
刚刚买回来,橘子树苗生命值90,高度105cm,没有结果子。
以后每一天树苗因为生长生命值-15,而高度+10cm。
苹果树在生命值大于等于30的情况下,每天结一颗果子。
橘子树在生命值大于等于60的情况下,每天结一颗果子。
两颗果树每一颗果子每一天消耗生命值2
每天你可以执行4个操作其中的一个:
0.        退出游戏
1.        浇水
2.        修剪高度
3.        摘果子
4.        什么也不做
选择浇水,可以输入水量(以公升计算)。每浇水一升,树苗生命值+1 。如果生命值超过100,则进行倒扣(浇水过多植物寿命减少)。如果当天选择浇水,则树苗当天高度立即+6(树苗吸水增长)。
选择摘果子,可以输入摘果数量,该数量不能大于结果数。
你的目标:使得树苗高度达到可以售卖的标准200cm。同时天数越短越好。达到200cm后的果树:苹果与橘子单个售价均为$1, 卖果子所得的钱将作为你的额外收入。收入越多越好。
注:超过200cm可以使用修剪功能减小树苗高度,但是剪切长度超过树苗高度,树苗即死亡。
我们来分析红色变动部分:
两棵树的初始高度和生命值现在都不一样了,显然,不能够在类中对高度和生命值进行统一初始化了,这里我们引入“构造函数”。请看代码:
  1. //代码3-5
  2. #include <stdio.h>
  3. const int HEIGHT_STANDARD = 200; //植物标准高度

  4. class Plant//植物类
  5. {
  6. public: //公开类中所有成员
  7.         int height = 0;
  8.         int health = 0;
  9.         int apple = 0;
  10.         int orange = 0;
  11.         Plant(int vHealth, int vHeight);           //构造函数
  12.         void Cut(int iCuttOffHeightByCentiMeter);  //剪切植物
  13.         void Water(int iWaterQuantityByLitery);    //浇水
  14.         void PickFruit(int howManyFruits);         //摘果子
  15. };

  16. Plant::Plant(int vHealth, int vHeight)
  17. {
  18.         health = vHealth;
  19.         height = vHeight;
  20. }

  21. void Plant::Cut(int iCuttOffHeightByCentiMeter) //成员函数
  22. {
  23.         if (height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  24.                 height -= iCuttOffHeightByCentiMeter; //剪切
  25.         else
  26.                 health = 0; //被剪死了
  27. }

  28. void Plant::Water(int iWaterQuantityByLitery) //成员函数
  29. {
  30.         int Orghealth = health; //记录浇水前的生命值
  31.         health += iWaterQuantityByLitery; //生命值等于浇水水量
  32.         health += 6; //每次浇水高度+6
  33.         if (health > 100) //生命值大于100
  34.                 health = Orghealth + 100 - health; //生命值倒扣
  35.         if (health < 0) //淹死了
  36.                 health = 0;
  37.         printf("\thealth+ %d\n\tHeight+ 6\n", health - Orghealth); //显示浇水后生命值以及高度的变化
  38. }

  39. void Plant::PickFruit(int howManyFruits) //成员函数
  40. {
  41.         int Apple = apple;   //苹果数
  42.         int Orange = orange; //橘子数
  43.                                                  //摘果
  44.         if (Apple > 0 && Apple - howManyFruits >= 0)
  45.                 apple -= howManyFruits;
  46.         if (Orange > 0 && Orange - howManyFruits >= 0)
  47.                 orange -= howManyFruits;
  48. }

  49. void HangARealDay(Plant* AppleTree, Plant* OrangeTree) //全局函数
  50. {
  51.         AppleTree->health -= 15 + AppleTree->apple * 2;
  52.         OrangeTree->health -= 15 + OrangeTree->orange * 2;
  53.         printf("\tHealth -15\n");
  54.         if (AppleTree->health > 20)
  55.                 AppleTree->height += 10;
  56.         if (OrangeTree->health > 20)
  57.                 OrangeTree->height += 10;
  58.         if (AppleTree->health >= 30)
  59.                 AppleTree->apple++;
  60.         if (OrangeTree->health >= 60)
  61.                 OrangeTree->orange++;
  62.         printf("Reports for apple tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", AppleTree->height, AppleTree->health, AppleTree->apple);
  63.         printf("Reports for orange tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", OrangeTree->height, OrangeTree->health, OrangeTree->orange);
  64. }

  65. int main()
  66. {
  67.         int iOption; //操作选择
  68.         int subOption;

  69.         int Day = 0; //天数

  70.         Plant* AppleTree = new Plant(100, 85);  //构建苹果树时使用类的构造函数,给参:生命值、高度
  71.         Plant* OrangeTree = new Plant(90, 105); //构建橘子树时使用类的构造函数,给参:生命值、高度
  72.         Plant* TargetPlant;

  73.         printf("Welcome!\nNow you have double saplings.\n");
  74.         printf("Begin your career as a gardener, and enjoy the game.\n");

  75.         while (1)
  76.         {
  77.                 Day++;
  78.                 printf("Days %d\n", Day);
  79.                 HangARealDay(AppleTree, OrangeTree);

  80.                 if (AppleTree->health <= 0 || OrangeTree->health <= 0)
  81.                         goto Lbl_Game_Over;
  82.                 printf("Choose a plant to operate.[0] for apple tree,[1] for orange tree.\n");
  83.                 scanf("%d", &iOption);
  84.                 if (!iOption && AppleTree->height != HEIGHT_STANDARD)
  85.                         TargetPlant = AppleTree;
  86.                 else if (iOption == 1 && OrangeTree->height != HEIGHT_STANDARD)
  87.                         TargetPlant = OrangeTree;
  88.                 else
  89.                         goto Lbl_Pass_Anyway;

  90.                 printf("[1]Water.[2]Cut.[3]Pick Fruits.[0]Give it up.\n");
  91.                 scanf("%d", &iOption);
  92.                 switch (iOption)
  93.                 {
  94.                 case 1:
  95.                         printf("\tInput water quantity:");
  96.                         scanf("%d", &subOption);
  97.                         TargetPlant->Water(subOption); //省略THIS
  98.                         break;
  99.                 case 2:
  100.                         printf("\tInput height to cut:");
  101.                         scanf("%d", &subOption);
  102.                         TargetPlant->Cut(subOption); //省略THIS
  103.                         break;
  104.                 case 3:
  105.                         printf("\tInput quantity to pick up:");
  106.                         scanf("%d", &subOption);
  107.                         TargetPlant->PickFruit(subOption); //省略THIS
  108.                         break;
  109.                 case 0:
  110.                         goto Lbl_Exit;
  111.                 Lbl_Pass_Anyway:
  112.                 default:
  113.                         printf("You have done nothing?\n");
  114.                 }
  115.         }
  116.         printf("%d Days,All plants were fit to sale! Any you got $%d for pocket money!\n", Day, AppleTree->apple + OrangeTree->orange);
  117.         return 0;
  118. Lbl_Exit:
  119.         printf("Wont you keep going on it?\n");
  120.         return 0;
  121. Lbl_Game_Over:
  122.         printf("One of your plants was die.");
  123.         return 0;
  124. }
复制代码

以上代码中,我们使用了构造函数来修改初始值。构造函数是和类同名的函数,而且构造函数的类中声明与类外实现不能加返回值说明。
然而“构造函数”不是浪得虚名,我们还可以这样创建Plant类的实例:
        Plant AppleTree(100, 85);
        Plant OrangeTree(90, 105);
在建造AppleTree和OrangeTree时,直接在对象名称后面带参的方式也是调用了构造函数,构造出了AppleTree与OrangeTree。
如果类中成员涉及到了动态内存管理。比如这样一个类:
  1. //代码3-6
  2. #include <iostream>
  3. #include <string.h>
  4. using namespace std;

  5. class Str
  6. {
  7. public:
  8.         char* ptrStr = NULL;
  9.         Str(char* vStr);
  10.         ~Str();
  11. };

  12. Str::Str(char* vStr)
  13. {
  14.         ptrStr = (char*)malloc(sizeof(char) * (strlen(vStr) + 1));
  15.         strcpy(ptrStr, vStr);
  16. }

  17. Str::~Str()
  18. {
  19.         free(ptrStr);
  20. }

  21. int main()
  22. {
  23.         Str varString = "abcdefg";
  24.         cout << varString.ptrStr << endl;
  25.         return 0;
  26. }
复制代码

如果我们不使用varString实例,而Str类中ptrStr指针又没有被释放,内存会逐渐堆积起来直到泄露。在与类名相同的函数前加上“~”符号的函数叫做“析构函数”。析构函数在类实例化出来的对象被销毁时自动调用。析构函数是用来“扫尾”的。举个骇人的例子:构造函数“接生”对象。析构函数“打理后事”,“安葬”对象,免得对象死后妨碍后人。
在C++之父的努力下,一个面向对象的C诞生了。它不仅支持C的全部属性用法,而且让C具备了更完善的描述世界的能力。
In the beginning I was not the best.
And the world was also not the best.
But I still know that I am who I am.
Because I think that it is good.
I have been working hard.
I have been keeping growth with the world.
And it was so.
回复 赞! 靠!

使用道具 举报

85

主题

175

回帖

3990

积分

用户组: 超级版主

No. 418

UID
418
精华
14
威望
53 点
宅币
1974 个
贡献
1582 次
宅之契约
0 份
在线时间
252 小时
注册时间
2014-8-9
 楼主| 发表于 2015-10-17 21:30:18 | 显示全部楼层
第四篇:人民内部问题

卜算子 OOP
面向过程边
踌躇止不前
已是信息爆炸世
重构来调校
造出结构类
包罗万象妙
待到革命完成时
却有问题闹。
我们来研究代码3-5里边的类:
将代码3-5的类单独拿出来:
  1. class Plant//植物类
  2. {
  3. public: //公开类中所有成员
  4.         int height = 0;
  5.         int health = 0;
  6.         int apple = 0;
  7.         int orange = 0;
  8.         Plant(int vHealth, int vHeight);           //构造函数
  9.         void Cut(int iCuttOffHeightByCentiMeter);  //剪切植物
  10.         void Water(int iWaterQuantityByLitery);    //浇水
  11.         void PickFruit(int howManyFruits);         //摘果子
  12. };
复制代码

我们可以看到,访问植物属性用的是什么办法呢?对了,直接读取公有属性height,health。这样做并不是很好的。因为如果误设了属性变量值,比如将health设置为负数。或者在if判断语句中不小心将==写成了=比如 if (MyPlant.height = 200) 然后导致了bug。怎么解决?将保存属性的变量与属性的读取设置过程分离开来,我们一起改造原先的类:
  1. //代码4-1
  2. class Plant//植物类
  3. {
  4. public:
  5.         int height = 0;
  6.         int health = 0;
  7.         int apple = 0;
  8.         int orange = 0;
  9.         Plant(int vHealth, int vHeight);           //构造函数
  10.         void Cut(int iCuttOffHeightByCentiMeter);  //剪切植物
  11.         void Water(int iWaterQuantityByLitery);    //浇水
  12.         void PickFruit(int howManyFruits);         //摘果子
  13.         bool ReduceHeight(int Height);             //消减高度
  14.         bool ReduceHealth(int Health);             //消减生命值
  15.         bool IncreaseFruit(int FruitsNumber);      //结果子
  16.         int GetHeight(void)                        //取得高度
  17.         {
  18.                 return height;
  19.         }
  20.         int GetHealth(void)                        //取得生命值
  21.         {
  22.                 return health;
  23.         }
  24.         int GetAppleFruit(void)                    //取得苹果数量
  25.         {
  26.                 return apple;
  27.         }
  28.         int GetOrangeFruit(void)                   //取得橘子数量
  29.         {
  30.                 return orange;
  31.         }
  32. };
复制代码

这样子修改以后我们可以调用GetXXX函数获取属性值,调用ReduceXXX函数消减高度和生命值,调用IncreaseFruit函数增加果子数量。
好了,问题来了。我们如何隐藏health,height,apple,orange属性避免其被误访问?办法是将其锁入private权限:
  1. //代码4-2
  2. #include <stdio.h>
  3. const int HEIGHT_STANDARD = 200; //植物标准高度

  4. class Plant//植物类
  5. {
  6. private:
  7.         int height = 0;
  8.         int health = 0;
  9.         int apple = 0;
  10.         int orange = 0;
  11. public:
  12.         Plant(int vHealth, int vHeight);           //构造函数
  13.         void Cut(int iCuttOffHeightByCentiMeter);  //剪切植物
  14.         void Water(int iWaterQuantityByLitery);    //浇水
  15.         void PickFruit(int howManyFruits);         //摘果子
  16.         bool ReduceHeight(int Height);             //消减高度
  17.         bool ReduceHealth(int Health);             //消减生命值
  18.         bool IncreaseFruit(int FruitsNumber);      //结果子
  19.         int GetHeight(void)                        //取得高度
  20.         {
  21.                 return height;
  22.         }
  23.         int GetHealth(void)                        //取得生命值
  24.         {
  25.                 return health;
  26.         }
  27.         int GetAppleFruits(void)                    //取得苹果数量
  28.         {
  29.                 return apple;
  30.         }
  31.         int GetOrangeFruits(void)                   //取得橘子数量
  32.         {
  33.                 return orange;
  34.         }
  35. };

  36. Plant::Plant(int vHealth, int vHeight)
  37. {
  38.         health = vHealth;
  39.         height = vHeight;
  40. }

  41. void Plant::Cut(int iCuttOffHeightByCentiMeter) //成员函数
  42. {
  43.         if (height - iCuttOffHeightByCentiMeter >= 0) //若剪切后的高度大于0
  44.                 height -= iCuttOffHeightByCentiMeter; //剪切
  45.         else
  46.                 health = 0; //被剪死了
  47. }

  48. void Plant::Water(int iWaterQuantityByLitery) //成员函数
  49. {
  50.         int Orghealth = health; //记录浇水前的生命值
  51.         health += iWaterQuantityByLitery; //生命值等于浇水水量
  52.         health += 6; //每次浇水高度+6
  53.         if (health > 100) //生命值大于100
  54.                 health = Orghealth + 100 - health; //生命值倒扣
  55.         if (health < 0) //淹死了
  56.                 health = 0;
  57.         printf("\thealth+ %d\n\tHeight+ 6\n", health - Orghealth); //显示浇水后生命值以及高度的变化
  58. }

  59. void Plant::PickFruit(int howManyFruits) //成员函数
  60. {
  61.         int Apple = apple;   //苹果数
  62.         int Orange = orange; //橘子数
  63.                                                  //摘果
  64.         if (Apple > 0 && Apple - howManyFruits >= 0)
  65.                 apple -= howManyFruits;
  66.         if (Orange > 0 && Orange - howManyFruits >= 0)
  67.                 orange -= howManyFruits;
  68. }

  69. bool Plant::ReduceHeight(int Height)
  70. {
  71.         if (this->height - Height >= 0)
  72.                 return false;
  73.         else
  74.                 this->height -= Height;
  75.         return true;
  76. }

  77. bool Plant::ReduceHealth(int Health)
  78. {
  79.         if (this->health - Health >= 0)
  80.                 return false;
  81.         else
  82.                 this->health -= Health;
  83.         return true;
  84. }

  85. bool Plant::IncreaseFruit(int FruitsNumber)
  86. {
  87.         if (FruitsNumber >= 0)
  88.         {
  89.                 apple += FruitsNumber;
  90.                 orange += FruitsNumber;
  91.                 return true;
  92.         }
  93.         else
  94.                 return false;
  95. }

  96. void HangARealDay(Plant* AppleTree, Plant* OrangeTree) //全局函数
  97. {
  98.         AppleTree->ReduceHealth(-(15 + AppleTree->GetAppleFruits() * 2));
  99.         OrangeTree->ReduceHealth(-(15 + OrangeTree->GetOrangeFruits() * 2));
  100.         printf("\t- Health\n");
  101.         if (AppleTree->GetHeight() > 20)
  102.                 AppleTree->ReduceHeight(-10);
  103.         if (OrangeTree->GetHealth() > 20)
  104.                 OrangeTree->ReduceHeight(-10);
  105.         if (AppleTree->GetHealth() >= 30)
  106.                 AppleTree->IncreaseFruit(1);
  107.         if (OrangeTree->GetHealth() >= 60)
  108.                 OrangeTree->IncreaseFruit(1);
  109.         printf("Reports for apple tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", AppleTree->GetHeight(), AppleTree->GetHealth(), AppleTree->GetAppleFruits());
  110.         printf("Reports for orange tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", OrangeTree->GetHeight(), OrangeTree->GetHealth(), OrangeTree->GetOrangeFruits());
  111. }

  112. int main()
  113. {
  114.         int iOption; //操作选择
  115.         int subOption;

  116.         int Day = 0; //天数

  117.         Plant* AppleTree = new Plant(100, 85);  //构建苹果树时使用类的构造函数,给参:生命值、高度
  118.         Plant* OrangeTree = new Plant(90, 105); //构建橘子树时使用类的构造函数,给参:生命值、高度
  119.         Plant* TargetPlant;

  120.         printf("Welcome!\nNow you have double saplings.\n");
  121.         printf("Begin your career as a gardener, and enjoy the game.\n");

  122.         while (1)
  123.         {
  124.                 Day++;
  125.                 printf("Days %d\n", Day);
  126.                 HangARealDay(AppleTree, OrangeTree);

  127.                 if (AppleTree->GetHealth() <= 0 || OrangeTree->GetHealth() <= 0)
  128.                         goto Lbl_Game_Over;
  129.                 printf("Choose a plant to operate.[0] for apple tree,[1] for orange tree.\n");
  130.                 scanf("%d", &iOption);
  131.                 if (!iOption && AppleTree->GetHeight() != HEIGHT_STANDARD)
  132.                         TargetPlant = AppleTree;
  133.                 else if (iOption == 1 && OrangeTree->GetHeight() != HEIGHT_STANDARD)
  134.                         TargetPlant = OrangeTree;
  135.                 else
  136.                         goto Lbl_Pass_Anyway;

  137.                 printf("[1]Water.[2]Cut.[3]Pick Fruits.[0]Give it up.\n");
  138.                 scanf("%d", &iOption);
  139.                 switch (iOption)
  140.                 {
  141.                 case 1:
  142.                         printf("\tInput water quantity:");
  143.                         scanf("%d", &subOption);
  144.                         TargetPlant->Water(subOption); //省略THIS
  145.                         break;
  146.                 case 2:
  147.                         printf("\tInput height to cut:");
  148.                         scanf("%d", &subOption);
  149.                         TargetPlant->Cut(subOption); //省略THIS
  150.                         break;
  151.                 case 3:
  152.                         printf("\tInput quantity to pick up:");
  153.                         scanf("%d", &subOption);
  154.                         TargetPlant->PickFruit(subOption); //省略THIS
  155.                         break;
  156.                 case 0:
  157.                         goto Lbl_Exit;
  158.                 Lbl_Pass_Anyway:
  159.                 default:
  160.                         printf("You have done nothing?\n");
  161.                 }
  162.         }
  163.         printf("%d Days,All plants were fit to sale! Any you got $%d for pocket money!\n", Day, AppleTree->GetAppleFruits() + OrangeTree->GetOrangeFruits());
  164.         return 0;
  165. Lbl_Exit:
  166.         printf("Wont you keep going on it?\n");
  167.         return 0;
  168. Lbl_Game_Over:
  169.         printf("One of your plants was die.");
  170.         return 0;
  171. }
复制代码

同样,类内部有函数不想公开的话,也可以锁入private权限。
至此,我们解决的人们内部“资源所有”问题的一半,即“私有财产圣神不可侵犯”。现在我们要在类的众多实例当中实行共产。
请看问题:如果我要让所有的同一个类造出来的实例都能访问一个变量,该怎么做?可能大家会回答:这还不简单,在类外部定义变量即可。那么我要求在类内部定义呢?这时大家打脸:意义何在?回答:如果我有“动物类(class Animal)”和“植物类(class Plant)”我是上帝,定义在一年(365天)的春季初(3月,差不多一年开始第90天)动物发情植物授粉。现在我要把所有的“动物类”的实例动物全部搬到南半球,植物都在北半球。南半球的春天是北半球的冬天。差不多发情期在第270天左右。好了现在设置两个共有变量: int植物授粉期 = 90;int 动物发情期 = 90; 在main函数中改:动物发情期 = 270; XXX;XXX;。如此这般我还不如在两个类中都申明一个静态变量static int Estrus = 90; 然后呢我只要改Animal类的一个实例,比如Cat,Cat.Estrus = 270;这时候Animal的实例不管是老虎还是狼,它们的发情期都变成了270.
为了好理解,我简单写了一下代码:
  1. //代码4-3
  2. #include <iostream>
  3. using namespace std;

  4. class Animal
  5. {
  6. private:
  7.         int health = 100;
  8.         int XXX;
  9. public:
  10.         static int estrus;

  11.         void Kill()
  12.         {
  13.                 health = 0;
  14.         }
  15. };

  16. class Plant
  17. {
  18. private:
  19.         int health = 100;
  20.         int XXX;
  21. public:
  22.         static int estrus;

  23.         void Kill()
  24.         {
  25.                 health = 0;
  26.         }
  27. };

  28. int Animal::estrus = 90; //使用静态成员变量必须用这种方式进行静态成员变量的初始化
  29. int Plant::estrus = 90;  //使用静态成员变量必须用这种方式进行静态成员变量的初始化

  30. int main()
  31. {
  32.         Plant Tree;
  33.         Plant Grass;
  34.         Animal Cat;
  35.         Animal Tiger;
  36.         Animal Wolf;
  37.         Animal Dog;
  38.        
  39.         cout << "Cat: " << Cat.estrus << endl;
  40.         cout << "Dog: " << Dog.estrus << endl;
  41.         cout << "Cat: " << Wolf.estrus << endl;
  42.         Dog.estrus = 270;
  43.         cout << "Cat: " << Cat.estrus << endl;
  44.         cout << "Dog: " << Dog.estrus << endl;
  45.         cout << "Cat: " << Wolf.estrus << endl;
  46.         return 0;
  47. }
复制代码

为啥要对静态成员变量进行初始化呢?
静态成员变量在实例化的时候并不是每实例化一次就为其分配一次内存。其实静态成员变量/函数就是全局的,只不过作用于这个类,受用于这个类的所有实例对象。
革命成功后随之而来的就是对政权的巩固,然而这个过程并不是一天两天,十年八年。甚至要维持到王朝结束的前一天。我们暂时解决的了人民的内部问题:分配了资产,个人的给个人,大家的大家共享。但是有一句话:One Problem Finished, Another Always Come.接下来的几章中,老C继续带大家探索实践发现“面向对象”。
In the beginning I was not the best.
And the world was also not the best.
But I still know that I am who I am.
Because I think that it is good.
I have been working hard.
I have been keeping growth with the world.
And it was so.
回复 赞! 靠!

使用道具 举报

0

主题

41

回帖

45

积分

用户组: 初·技术宅

UID
3351
精华
0
威望
2 点
宅币
0 个
贡献
0 次
宅之契约
0 份
在线时间
0 小时
注册时间
2018-1-14
发表于 2018-1-14 15:35:20 | 显示全部楼层
可以可以!!
回复

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-4-26 04:20 , Processed in 0.051651 second(s), 30 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表