本帖最后由 linexs 于 2015-11-21 23:54 编辑
/*
要求: * 类名、属性名、属性类型、方法名、方法参数、方法返回值自拟 * 自己写main函数测试设计是否合理
1.设计一个”狗“类 1> 属性 * 颜色 * 速度(单位是m/s) * 性别 * 体重(单位是kg)
2> 行为 * 吃:每吃一次,体重增加0.5kg,输出吃完后的体重 * 吠(叫):输出所有的属性 * 跑:每吃一次,体重减少0.5kg,输出速度和跑完后的体重 * 比较颜色:跟别的狗比较颜色,如果一样,返回YES,不一样,返回NO * 比较速度:跟别的狗比较速度,返回速度差(自己的速度 - 其他狗的速度)
*/
#import <Foundation/Foundation.h>
@interface Dog : NSObject {
@public
NSString *_name; int _color; float _speed; char _sex; float _weight; } -(void)eat; -(void)fate; -(void)run; -(NSString *)cmpColor:(Dog *) otherDog; -(int)cmpSpeed:(Dog *) otherDog;
@end
@implementation Dog
-(void)eat{ _weight+=0.5; NSLog(@"%@,体重:%.2lf",_name,_weight); }
-(void)fate{ NSLog(@"%@,颜色:%d,性别%c,体重:%.2lf,速度:%.2lf\n",_name,_color,_sex,_weight,_speed); }
-(void)run{ _weight-=0.5; NSLog(@"%@,体重:%.2lf",_name,_weight); } -(NSString *)cmpColor:(Dog *) otherDog {
if (_color == otherDog ->_color) { return @"YES"; } else { return @"NO"; }
} -(int)cmpSpeed:(Dog *) otherDog {
return _speed - otherDog->_speed; }
@end
int main(int argc, const char * argv[]) { @autoreleasepool { // insert code here...
Dog * yellow = [Dog new]; yellow->_name= @"大黄"; yellow->_color= 1; yellow->_sex= 'm'; yellow->_weight= 125; yellow->_speed= 12;
Dog * black = [Dog new]; black->_name= @"小黑"; black->_color= 2; black->_sex= 'f'; black->_weight= 75; black->_speed= 10;
[yellow eat]; [yellow fate]; [yellow run];
NSLog(@"%@和%@的颜色一样吗?%@",yellow->_name,black->_name,[yellow cmpColor:black]); NSLog(@"%@和%@的速度差是:%d",yellow->_name,black->_name,[yellow cmpSpeed:black]);
NSLog(@"The, end!"); } return 0; }
|