/* 设计一个”狗“类 1> 属性 * 颜色 * 速度(单位是m/s) * 性别 * 体重(单位是kg)
2> 行为 * 吃:每吃一次,体重增加0.5kg,输出吃完后的体重 * 吠(叫):输出所有的属性 * 跑:每吃一次,体重减少0.5kg,输出速度和跑完后的体重 * 比较颜色:跟别的狗比较颜色,如果一样,两个值做减法得零,返回NO(零值),不一样,做减法得到非零值,返回YES(1) * 比较速度:跟别的狗比较速度,返回速度差(自己的速度 - 其他狗的速度) */
#import <Foundation/Foundation.h>
//定义枚举类型 类型名 color typedef enum color{kColorBlack,kColorWhite,kColorYellow} iColor; //定义枚举的性别 typedef enum sex{kSexGong,kSexMu,kSexYao} iSex;
#pragma mark - 狗类
//类的声明 @interface Dog:NSObject { @public iColor _color; int _speed;
iSex _sex; float _weight; }
-(void)eat; -(void)bark; -(void)run; -(BOOL)compareColorWithOther:(Dog *)dog; -(int)compareSpeedWtihOther:(Dog *)dog; @end
@implementation Dog -(void)eat{ _weight += 0.5f; NSLog(@"正在吃东西,_weight = %.2f",_weight);
} -(void)bark{ NSLog(@"颜色:%d,体重:%.2f,速度:%d,性别:%d",_color,_weight,_speed,_sex);
} -(void)run{ _weight -= 0.5f; NSLog(@"正在疯跑,_weight = %.2f",_weight);
} -(BOOL)compareColorWithOther:(Dog *)dog{ if(_color == dog->_color){ return YES; } return NO; } -(int)compareSpeedWtihOther:(Dog *)dog{ return _speed - dog->_speed; } @end
int main(int argc, const char * argv[]) { @autoreleasepool { Dog *dog = [Dog new];
dog->_color = kColorBlack; dog->_sex = kSexGong; dog->_speed = 200; dog->_weight = 22; [dog eat]; //22.5 [dog eat]; [dog eat]; [dog run]; [dog bark]; Dog *byd = [Dog new]; byd->_color = kColorBlack; byd->_sex = kSexGong; byd->_speed = 180; byd->_weight = 50;
BOOL isYES = [dog compareColorWithOther:byd]; //返回BOOL if (isYES) { NSLog(@"颜色相同"); }else{ NSLog(@"颜色不同"); } int num = [dog compareSpeedWtihOther:byd]; NSLog(@"两条狗的速度差:%d",num); } return 0; }
|