开更老C的新作品:Practice With OO Method in C/C++: A Game Of Gardener(C/C++面向对象方法实践:园丁游戏) 作者:cyycoish。转载请注明作者出处,否则视为侵权。
这篇文章主要向大家介绍面向对象的实现方法。本文面向于那些对面向对象编程概念摸不着头脑的人们。接下来会使用C(注:C不是面向对象的语言),C++来加以说明。因为本人水平有限,如有错误之处欢迎指正批评共同进步。
printf("Reports for apple tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", AppleTree->GetHeight(), AppleTree->GetHealth(), AppleTree->GetAppleFruits());
printf("Reports for orange tree:\n\tHeight: %d/200\n\tHealth: %d/100\n\tFruits: %d\n", OrangeTree->GetHeight(), OrangeTree->GetHealth(), OrangeTree->GetOrangeFruits());
}
int main()
{
int iOption; //操作选择
int subOption;
int Day = 0; //天数
Plant* AppleTree = new Plant(100, 85); //构建苹果树时使用类的构造函数,给参:生命值、高度
Plant* OrangeTree = new Plant(90, 105); //构建橘子树时使用类的构造函数,给参:生命值、高度
Plant* TargetPlant;
printf("Welcome!\nNow you have double saplings.\n");
printf("Begin your career as a gardener, and enjoy the game.\n");
while (1)
{
Day++;
printf("Days %d\n", Day);
HangARealDay(AppleTree, OrangeTree);
if (AppleTree->GetHealth() <= 0 || OrangeTree->GetHealth() <= 0)
goto Lbl_Game_Over;
printf("Choose a plant to operate.[0] for apple tree,[1] for orange tree.\n");
scanf("%d", &iOption);
if (!iOption && AppleTree->GetHeight() != HEIGHT_STANDARD)
TargetPlant = AppleTree;
else if (iOption == 1 && OrangeTree->GetHeight() != HEIGHT_STANDARD)
TargetPlant = OrangeTree;
else
goto Lbl_Pass_Anyway;
printf("[1]Water.[2]Cut.[3]Pick Fruits.[0]Give it up.\n");
scanf("%d", &iOption);
switch (iOption)
{
case 1:
printf("\tInput water quantity:");
scanf("%d", &subOption);
TargetPlant->Water(subOption); //省略THIS
break;
case 2:
printf("\tInput height to cut:");
scanf("%d", &subOption);
TargetPlant->Cut(subOption); //省略THIS
break;
case 3:
printf("\tInput quantity to pick up:");
scanf("%d", &subOption);
TargetPlant->PickFruit(subOption); //省略THIS
break;
case 0:
goto Lbl_Exit;
Lbl_Pass_Anyway:
default:
printf("You have done nothing?\n");
}
}
printf("%d Days,All plants were fit to sale! Any you got $%d for pocket money!\n", Day, AppleTree->GetAppleFruits() + OrangeTree->GetOrangeFruits());
int Animal::estrus = 90; //使用静态成员变量必须用这种方式进行静态成员变量的初始化
int Plant::estrus = 90; //使用静态成员变量必须用这种方式进行静态成员变量的初始化
int main()
{
Plant Tree;
Plant Grass;
Animal Cat;
Animal Tiger;
Animal Wolf;
Animal Dog;
cout << "Cat: " << Cat.estrus << endl;
cout << "Dog: " << Dog.estrus << endl;
cout << "Cat: " << Wolf.estrus << endl;
Dog.estrus = 270;
cout << "Cat: " << Cat.estrus << endl;
cout << "Dog: " << Dog.estrus << endl;
cout << "Cat: " << Wolf.estrus << endl;
return 0;
}
复制代码
为啥要对静态成员变量进行初始化呢?
静态成员变量在实例化的时候并不是每实例化一次就为其分配一次内存。其实静态成员变量/函数就是全局的,只不过作用于这个类,受用于这个类的所有实例对象。
革命成功后随之而来的就是对政权的巩固,然而这个过程并不是一天两天,十年八年。甚至要维持到王朝结束的前一天。我们暂时解决的了人民的内部问题:分配了资产,个人的给个人,大家的大家共享。但是有一句话:One Problem Finished, Another Always Come.接下来的几章中,老C继续带大家探索实践发现“面向对象”。