#import <Foundation/Foundation.h>
#pragma mark dog的声明
@interface dog : NSObject
{
@public
NSString *_color;
float _velocity;
NSString *_sex;
float _weight;
}
//function declaration
-(float)eat:(int) num and:(float) weight;
-(void)call;
-(float)run:(int)num and:(float)weight;
-(int)cmpColor:(dog *) dog2;
-(float)cmpVelocity:(dog *)dog;
@end
#pragma mark -
#pragma mark dog的实现
@implementation dog
/**
* 狗吃一次食物体重增加0.5kg
*
* @param num 吃食物的次数
* @param weight 当前的体重
*
* @return 吃完后的体重
*/
-(float)eat:(int) num and:(float) weight{
return weight += num*0.5;
}
/**
* 描述狗的全部属性
*/
-(void)call {
NSLog(@"dog's color is %@",_color);
NSLog(@"dog's velocity is %.2fkm/s",_velocity);
NSLog(@"dog's sex is %@",_sex);
NSLog(@"dog's weight is %.2fkg",_weight);
}
/**
* 狗没跑一次体重减少0.5kf
*
* @param num 跑的次数
* @param weight 当前体重
*
* @return 跑完后的体重
*/
-(float)run:(int)num and:(float)weight{
return weight -= num*0.5;
}
/**
* 比较两只狗的颜色
*
* @param dog1 dog1传过来的内容:颜色
* @param dog2 dog2传过来的内容:颜色
*
* @return 相同返回值1,不同返回值0.
*/
-(int)cmpColor:(dog *) dog2{
BOOL flag = YES;
if (_color == dog2->_color) {
return flag;
}
else
return flag;
}
/**
* 比较两只狗的速度,用第一只减去第二只的
*
* @param dog1 dog1传过来的值:速度
* @param dog2 dog2传过来的值:速度
*
* @return 第一只狗的速度减去第二只够的速度。
*/
-(float)cmpVelocity:(dog *)dog{
return _velocity - dog->_velocity;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
dog *dog1 = [dog new];
dog1->_color = @"yellow";
dog1->_sex = @"white";
dog1->_velocity = 13.5;
dog1->_weight = 34.6;
[dog1 call];
NSLog(@"%.2f",[dog1 eat:6 and:dog1->_weight]);
NSLog(@"%.2f",[dog1 run:1 and:dog1->_weight]);
dog *dog2 = [dog new];
dog2->_color = @"yellow";
dog2->_velocity = 11.5;
if ([dog1 cmpColor:dog2] == 1) {
NSLog(@"same color");
}
else
NSLog(@"dofferent color");
NSLog(@"%.2f",[dog1 cmpVelocity:dog2]);
}
return 0;
}
注释中有详细思路。