一 概述
- 本文通过一个实例来讲解如何设计类更加合理有效
- 类:人:成员变量:性别,生日,体重,最喜欢的颜色,狗,方法:吃,跑步,遛狗,喂狗
- 类:狗:成员变量:体重,毛色;方法:吃,跑
二 代码实现
复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
#include <Foundation/Foundation.h> typedef enum{ SexMan, SexWoman }Sex; typedef struct { int year; int month; int day; } Date; typedef enum { ColorBlack, ColorRed, ColorGreen }Color; //---------------狗定义------------ @interface Dog : NSObject { @public double weight;//体重 Color curColor;//毛色 } -(void)eat; -(void)run; @end @implementation Dog -(void)eat { weight+=1; NSLog(@"狗吃完这次后的体重是%f",weight); } -(void)run { weight-=1; NSLog(@"狗跑完这次后的体重是%f",weight); } @end //---------------人定义------------ @interface Student : NSObject { @public Sex sex;//性别 Date birthday;//生日 double weight;//体重 Color favColor;//最喜欢的颜色 NSString *name; Dog *dog; } -(void)eat; -(void)run; -(void)print; -(void)liuDog; -(void)weiDog; @end @implementation Student -(void)eat { weight+=1; NSLog(@"吃完这次后的体重是%f",weight); } -(void)run { weight-=1; NSLog(@"跑完这次后的体重是%f",weight); } -(void)print { NSLog(@"性别=%d,喜欢的颜色=%d,姓名=%@,生日=%d-%d-%d",sex,favColor,name,birthday.year,birthday.month,birthday.day); } -(void)liuDog { [dog run]; } -(void)weiDog { [dog eat]; } @end int main() { Student *s=[Student new]; Dog *d=[Dog new]; d->curColor=ColorGreen; d->weight=20; s->dog=d; [s liuDog]; [s weiDog]; return 0; } void test() { Student *s=[Student new]; s->weight=50; s->sex=SexMan; s->name=@"jack"; //Date d={2020,3,30}; //s->birthday=d; //s->birthday.year=2020; //s->birthday.month=3; //s->birthday.day=30; Date d=s->birthday; d.year=2020; d.month=3; d.day=30; s->birthday=d; s->favColor=ColorBlack; [s eat]; [s eat]; [s run]; [s run]; [s print]; } |
三 代码设计说明
- 可以将性别设计成枚举类
- 可以将生日设计成结构体