| 
 
| 设计一个”狗“类 1> 属性
 * 颜色
 * 速度(单位是m/s)
 * 性别
 * 体重(单位是kg)
 
 2>行为
 * 吃:每吃一次,体重增加0.5kg,输出吃完后的体重
 * 吠(叫):输出所有的属性
 * 跑:每吃一次,体重减少0.5kg,输出速度和跑完后的体重
 * 比较颜色:跟别的狗比较颜色,如果一样,两个值做减法得零,返回NO(零值),不一样,
 做减法得到非零值,返回YES(1)
 * 比较速度:跟别的狗比较速度,返回速度差(自己的速度 - 其他狗的速度)
 
 
 复制代码#import <Foundation/Foundation.h>
//写一个狗的类
// 类名:Dog
// 实例变量  _color _speed _sex _weight
// 行为: eat jiao run compareColor compareSpeed
@interface Dog:NSObject
{
    @public
    //数据类型 _实例变量名
     NSString * _color;
    int _speed;
    NSString * _sex;
    float _weight;
}
//方法声明(无参 有参)
-(float)eat;
-(void)jiao;
-(float)run;
//-(BOOL)compareColor:(NSString*)otherColor;
-(int)compareSpeed:(int )otherSpeed;
@end
@implementation Dog
//方法名
-(float)eat{
    _weight+=0.5;
    return _weight;
}
-(void)jiao{
    NSLog(@"我的颜色是%@,速度是%d,性别是%@,体重%.2f",_color,_speed,_sex,_weight);
}
-(float)run{
    _weight-=0.5;
    return _weight;
}
-(BOOL)compareColor:(NSString *)otherColor{
    
    //if(_color isEqualTo otherColor){
    if(_color == otherColor){
        return 0;
    }else
    return 1;
}
-(int)compareSpeed:(int )otherSpeed{
    
    return _speed-otherSpeed;
}
@end
int main(){
    @autoreleasepool {
        Dog *dog=[Dog new];
        dog->_speed=20;
        dog->_weight=30;
        dog->_color=@"green";
        dog->_sex=@"mother";
        [dog eat];
        NSLog(@"wo吃东西了,我的体重%.2f",dog->_weight);
        [dog run];
        NSLog(@"wo运动了,我的体重%.2f",dog->_weight);
        [dog jiao];
        bool cp=[dog compareColor:@"black"];
        NSLog(@"我的yanse:%@,比较结果wei:%d",dog->_color,cp);
        int cS=[dog compareSpeed:10];
        
        NSLog(@"速度差=%d",cS);
    }
}
 | 
 |