美文网首页八天学会OC
第02天OC语言(10):对象作为返回值

第02天OC语言(10):对象作为返回值

作者: liyuhong | 来源:发表于2017-07-13 11:05 被阅读7次
    一、概念
    二、代码
    #import <Foundation/Foundation.h>
    #pragma mark 类
    #pragma mark - 3.弹夹
    
    @interface Clip : NSObject
    {
    @public
        int _bullet;
    }
    - (void)addBullet;
    @end
    
    @implementation Clip
    - (void)addBullet
    {
        // 上子弹
        _bullet = 10;
    }
    @end
    
    #pragma mark - 2.枪
    @interface Gun : NSObject
    {
    @public
        Clip *clip; // 弹夹
        
    }
    // 注意 : 在企业开发中 千万不要随意修改一个方法
    - (void)shoot;
    // 想要射击,必须传递弹夹
    - (void)shoot:(Clip *)c;
    
    @end
    
    @implementation Gun
    
    - (void)shoot:(Clip *)c
    {
        
        if (c != nil) { // nul == null == 没有值
            // 判断有没有子弹
            if (c->_bullet > 0) {
                c->_bullet -=1;
                NSLog(@"打了一枪 %i",c->_bullet);
            }
            else
            {
                NSLog(@"没有子弹了");
            }
        }
        else
        {
            NSLog(@"没有弹夹 ,请换弹夹");
        }
    }
    @end
    #pragma mark - 1.士兵
    @interface Soldier : NSObject
    {
    @public
        NSString *_name;
        double _height;
        double _weight;
    }
    - (void)fire:(Gun *)gun;
    // 开火,给士兵 一把枪,和弹夹
    - (void)fire:(Gun *)g Clip:(Clip *)clip;
    @end
    
    @implementation Soldier
    
    - (void)fire:(Gun *)g
    {
        [g shoot];
    }
    
    - (void)fire:(Gun *)g Clip:(Clip *)clip
    {
        if (g != nil &&
            clip != nil){
            [g shoot:clip];
        }
    }
    @end
    
    #pragma mark - 0.商店
    
    @interface Shop : NSObject
    
    // 买枪
    + (Gun *)buyGun:(int)monery;
    // 买弹夹
    + (Clip *)buyClip:(int)monery;
    
    @end
    
    @implementation Shop
    
    + (Gun *)buyGun:(int)monery
    {
        // 1.创建一把枪
        Gun *g = [Gun new]; // 通过 new 创建出来的对象 存储在堆中,堆中的数据 不会自动释放
        // 2.返回一把枪
        return g;
    }
    // 买弹夹
    + (Clip *)buyClip:(int)monery
    {
        // 1.创建弹夹
        Clip *clip = [Clip new];
        [clip addBullet]; // 添加子弹
        // 2.返回弹夹
        return clip;
    }
    
    @end
    
    
    
    #pragma mark - main函数
    int main(int argc, const char * argv[])
    {
        // 1.创建士兵
        Soldier *s = [Soldier new];
        s->_name = @"lyh";
        s->_height = 1.71;
        s->_weight = 65.0;
        
        // 商家对象
    //    Shop *shop = [Shop new];
        
        // 2.创建枪
    //    Gun *gp = [Gun new];
        // 2.购买手枪
        Gun *gp = [Shop buyGun:888];
        
        
        // 3.创建弹夹
    //    Clip *clip = [Clip new];
    //    [clip addBullet];
        
        // 3. 购买弹夹
        Clip *clip = [Shop buyClip:88];
        
        // 4.士兵开火
        [s fire:gp Clip:clip];
    
        
        return 0;
    }
    

    相关文章

      网友评论

        本文标题:第02天OC语言(10):对象作为返回值

        本文链接:https://www.haomeiwen.com/subject/xwcphxtx.html