1
//// Pet.m// 小黄鸡//// Created by 裴烨烽 on 14-3-18.// Copyright (c) 2014年 裴烨烽. All rights reserved.//#import "Pet.h"#define MAX_Energy 10@implementation Pet //自定义的初始化函数 -(Pet *)initWithName:(NSString *)n andAge:(int)a { //1.调用父类的初始化 self=[super init]; //2.执行自己的初始化 if(self) { name=n; age=a; energy=5; } //返回自己 return self; } //吃东西 -(void)eat { //接受输入C的字符串 char buffer1[20]; scanf("%s",buffer1); //c字符串=>oc的字符串 NSString *foodStr=[NSString stringWithUTF8String:buffer1]; //取字符串的整数部分 int foods =[foodStr intValue]; if(foods<=0) { NSLog(@"你他妈的耍我!"); } else { if(energy>=MAX_Energy) { NSLog(@"我实在是吃不下去了"); } else{ energy+=foods; if(energy
2
//// Pet.h// 小黄鸡//// Created by 裴烨烽 on 14-3-18.// Copyright (c) 2014年 裴烨烽. All rights reserved.//#import//宠物类@interface Pet : NSObject{ NSString *name;//姓名 int age; //年龄 int energy; //能量值}//自定义的初始化函数-(Pet *)initWithName:(NSString *)name andAge:(int)age;//吃东西-(void)eat;//聊天-(void)talk:(NSString *)question;//再见-(void)sayGoodBye;@end
3
//// main.m// 小黄鸡//// Created by 裴烨烽 on 14-3-18.// Copyright (c) 2014年 裴烨烽. All rights reserved.//#import#import "Pet.h"int main(int argc, const char * argv[]){ @autoreleasepool {//创建对象,初始化对象,并且让指针类型的变量MyPet指向这个对象的内存地址 Pet *mypet =[[Pet alloc ]initWithName:@"小强" andAge:3]; //是否结束 bool ifEnd=false; //判断,如果没有结束,执行循环体 while (ifEnd==false) { //接受输入c的字符串 char buffer1[20]; scanf("%s",buffer1); //c字符串=>OC字符串 NSString *question=[NSString stringWithUTF8String:buffer1]; if([question isEqualToString:@"exit"]) { [mypet sayGoodBye]; ifEnd=true; } else { //回答问题 [mypet talk:question]; } } } return 0;}