对象作为返回值

//
//  main.m
//  对象作为返回值:对象作为返回值,主要是掌握:
//在成员方法中创建的对象,是局部变量,但是这个局部变量存储在堆当中,方法执行完后不会自动的释放

#import <Foundation/Foundation.h>

//士兵在兵工厂买枪和子弹,然后进行射击

//弹夹类
@interface Clip : NSObject
{
    @public
    int _bullet; // 子弹数
}
- (void)addBullet; // 上子弹
@end
@implementation Clip

- (void)addBullet{
    _bullet=10;
}
@end

//枪类
@interface Gun : NSObject
{
    @public
    Clip* _clip;
}
- (void)shoot:(Clip*)mClip;
@end
@implementation Gun

- (void)shoot:(Clip *)mClip{
    if (mClip->_bullet>0) {
        NSLog(@"发射了一次,还剩%i个子弹",--mClip->_bullet);
    }
}
@end

//兵工厂类
@interface Shop : NSObject
{
}
+ (Gun*)buyGun:(int)money;
+ (Clip*)buyClip:(int)money;
@end
@implementation Shop

+ (Clip *)buyClip:(int)money{
    if (money>10) {
        Clip *tmpClip=[Clip new];
        tmpClip->_bullet=10;
        return tmpClip;
    }else{
        NSLog(@"资金不足");
        return nil;
    }
}
+ (Gun *)buyGun:(int)money{
    if (money>10) {
        Gun *tmpGun=[Gun new];
        return tmpGun;
    }else{
        NSLog(@"资金不足");
        return nil;
    }
}
@end

//士兵类
@interface Slodier : NSObject
{
@public
    NSString *_name;
    int _height;
    int _weight;
}
- (void)fire:(Gun*)mGun and:(Clip*)mClip;
@end

@implementation Slodier

- (void)fire:(Gun *)mGun and:(Clip *)mClip{
    [mGun shoot:mClip];
}
@end

int main(int argc, const char * argv[]) {

//    创建一个士兵对象
    Slodier *ps=[Slodier new];
    ps->_name=@"哈士奇";
    ps->_height=20;
    ps->_weight=20;
//    买枪和弹夹(这里本想让士兵自己买枪和弹夹的,士兵是有购买的功能的,这里直接调用了)
    Clip *pc=[Shop buyClip:20];
    Gun *pg=[Shop buyGun:20];
//    射击
    [ps fire:pg and:pc];

    return 0;
}
原文地址:https://www.cnblogs.com/imChay/p/5590243.html