类的合理设计
2015-11-19 22:55
393 查看
#import <Foundation/Foundation.h> typedef enum {//枚举 SexMan, SexWoman }Sex; typedef struct { int year; int month; int day; }Data; typedef enum { ColorBlack, ColorRed, ColorGreen }Color; @interface Dog : NSObject { @public double weight; //体重 Color curColor; //毛色 } - (void)run; - (void)eat; @end @implementation Dog - (void)eat { //每吃一次,体重加1 weight += 1; NSLog(@"狗吃完这次后的体重是%.2f",weight); } - (void)run { weight -= 1; NSLog(@"狗跑完这次后的体重是%.2f",weight); } @end /* 学生 成员变量:性别、生日、体重、最喜欢的颜色、狗(体重、毛色、吃、跑) 方法:吃、跑步、遛狗(让狗跑)、喂狗(让狗吃)、 */ @interface Student : NSObject { @public Sex sex; //性别 Data birthday; //生日 double weight; //体重(kg) Color favColor; //最喜欢的颜色 char *name; //重点 Dog *dog;//任何OC对象肯定是用指针来指的 } - (void)eat; - (void)run; - (void)print; - (void)liuDog; - (void)weiDog; @end @implementation Student - (void)liuDog { //让狗跑起来(调用狗的run方法) [dog run]; } - (void)weiDog { //让狗吃东西(调用狗的eat方法) [dog eat]; } - (void)print { NSLog(@"性别=%d,喜欢的颜色=%d,姓名=%s,生日=%d-%d-%d",sex,favColor,name,birthday.year,birthday.month,birthday.day); } - (void)eat { //每吃一次,体重加1 weight += 1; NSLog(@"学生吃完这次后的体重是%.2f",weight); } - (void)run { weight -= 1; NSLog(@"学生跑完这次后的体重是%.2f",weight); } @end int main() { Student *s = [Student new]; Dog *sdog = [Dog new]; sdog->curColor = ColorGreen; sdog->weight = 20; s->dog = sdog;//对象中又有对象 [s liuDog]; [s weiDog]; s->weight = 50; //性别 s->sex = SexMan; //生日 //s->birthday = {2011, 9, 10};错误 Data d ={1993 , 9 , 9}; s->birthday = d; /* s->birthday.year = 1993; s->birthday.month = 9; s->birthday.day = 9; */ //姓名 s->name = "DaShu"; //喜欢的颜色 s->favColor = ColorBlack; [s eat]; [s eat]; [s run]; [s run]; [s print]; return 0; }
相关文章推荐
- Objective-C的内省(Introspection)用法小结
- Objective-C中常用的结构体NSRange,NSPoint,NSSize(CGSize),NSRect实例分析
- Objective-C中NSNumber与NSDictionary的用法简介
- Objective-C中NSLog输出格式大全
- 全面解析Objective-C中的block代码块的使用
- Swift调用Objective-C编写的API实例
- Swift、Objective-C、Cocoa混合编程设置指南
- Objective-c代码如何移植为Swift代码 Objective-c代码转移到Swift过程介绍
- Swift调用Objective-C代码
- 以实例讲解Objective-C中的KVO与KVC机制
- objective-c中生成随机数的方法
- 在Swift中使用Objective-C编写类、继承Objective-C类
- Swift能代替Objective-C吗?
- Objective-C 消息传递机制详解
- 在一个项目中同时使用Swift和Objective-C代码混合编程的方法
- vm安装mac os x 10.7 lion
- objective-c(一)
- objective-c(二)
- objective-c(三)