A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© YuePr 中级黑马   /  2015-12-8 20:24  /  1011 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. // [代码说明:类的多态体现及用途]
  2. // 说明:下方为伪代码,其中police是一个继承自person的类,thief 也是一个继承自person的类
  3. @interface Person :NSObjec{      //---->父类
  4. NSStrint *_name;
  5. }
  6. -(void)setName:(NSString *)name;
  7. -(void)name;
  8. @end
  9. @implementation
  10. -(void)setName:(NSString *)name{
  11.     _name  = name;
  12. }
  13. -(NSString*)name{
  14.      return _name;
  15. }
  16. @end
  17. @interface Police :person{}        //子类police的声明
  18. @end  
  19. .............实现省略
  20. @interface Thief :person{}          //子类thief的声明
  21. @end
  22. .............实现省略
  23. void methdDisplay(Person *per)
  24. {
  25.     NSlog(@"methdDISplay is %@",per.name);
  26. }
  27. int main()
  28. {
  29.     Police *policeMan = [Police new];
  30.     policeMan.name = @"police SIR";
  31.     methdDisplay(policeMan);        //此处打印的是:methdDISplay is police SIR
  32.    Thief *thiefA = [Thief new];
  33.     thiefA.name = @"xiaotou A";
  34.     methdDisplay(thiefA);            //此处打印的是:methdDISplay is xiaotou A
  35.     return 0;
  36. }
复制代码

4 个回复

倒序浏览
本帖最后由 YuePr 于 2015-12-10 22:49 编辑

注意使用多态的时候,是子类中,有和父类同名的对象方法是,可以通过父类的指针直接访问子类的方法。
Person  ->  父类
Police   ->  子类
person *per = [Police new];
((police *)per).setGunType = @"AK47";
则此时  访问子类中特有的方法时 需要进行类型强转。
回复 使用道具 举报
可以是可以,但是还是id更实用
回复 使用道具 举报
iOS-lye 来自手机 中级黑马 2015-12-11 12:19:47
板凳
多态是什么来自: iPhone客户端
回复 使用道具 举报
使用id指针在后期的协议与代理学习时,可以使用   @property in<需要遵守的协议名> 成员变量名,则可以完成多态方式下的协议与代理操作,即任意何种类对象的指针只需要遵守了指定协议即可达到限定的条件。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马