zoukankan      html  css  js  c++  java
  • Objective

    在前面, 我们知道了继承的注意事项, 其实继承还有使用的场合, 还有组合的注意事项:


    首先我们来说使用场合:

    #import <Foundation/Foundation.h>
    
    @interface Score : NSObject
    {
        int _mathScore;
        int _chinaseScore;
    }
    @end
    
    @implementation Score
    @end
    
    @interface Student : NSObject
    {
        int _mathScore;
        int _chinaseScore;
        int _age;
    }
    @end
    
    @implementation Student
    @end
    
    int main()
    {
        return 0;
    }



    有些人看到这个例子, 第一件事就是看到StudentScore有两个相同的属性, 然后就把Student的两个属性干掉, 把Student直接继承Score, 比如:

    #import <Foundation/Foundation.h>
    
    @interface Score : NSObject
    {
        int _mathScore;
        int _chinaseScore;
    }
    @end
    
    @implementation Score
    @end
    
    @interface Student : Score
    {
        int _age;
    }
    @end
    
    @implementation Student
    @end
    
    int main()
    {
        return 0;
    }

    虽然看上去是可以行, 但实际上这是不合理的, Score是分数, Student是人, 拿一个人去继承分数, 这合理吗?? 人 ≠ 分数, 所以这样子是不行, 我们得找另外一个方法:

    @interface Score : NSObject
    {
        int _mathScore;
        int _chinaseScore;
    }
    @end
    
    @implementation Score
    @end
    
    @interface Student : NSObject
    {
        Score *_score;
        int _age;
    }
    @end
    
    @implementation Student
    @end


    用一个指针指向于Score, 那么Student也会拥有这两个属性, 而且不会存在不合理, 这个就是组合~~





    好了, 这次我们就到这里, 下次我们继续~~~

  • 相关阅读:
    Delphi中 弹出框的用法
    VC++代码上传到VSS上 注意事项
    VC++ 屏蔽掉警告
    IIS LocalDB 登录失败
    SVN版本回滚实战
    Git常用命令图解
    C# 百度API地址坐标互相转换
    Quartz.NET浅谈一 : 简单Job使用(定时发送QQ邮件)
    发布自己的类库包到Nuget
    C# 常用日期取得
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4282847.html
Copyright © 2011-2022 走看看