作为Object C语法的特性之一Posing

来源:互联网 发布:数字病理 人工智能 编辑:程序博客网 时间:2024/05/21 17:51

Posing
扮演:作为Object C语法的特性之一。

通过poseAs方法来做到扮演的目的。

扮演的作用:无需要定义子类对象和初始化,就可以通过父类扮演子类来操作

。(等价于子类的直接操作,类似父类转子类)。
例子:
#import "Fraction.h"

@interface FractionB: Fraction
-(void) print;
@end

@implementation FractionB;
-(void) print
{
  printf (" (%i/%i) ", numerator, denominator);
}
@end


int main (int argc, char *argv[])
{
  Fraction *a;
  Fraction *b;
  Fraction *result;

  [FractionB poseAs: [Fraction class]];

  a = [[Fraction alloc] init];
  b = [[Fraction alloc] init];

  [a setTo: 1 over: 3];
  [b setTo: 2 over: 5];

  [a print]; printf (" + "); [b print]; printf (" = ");
  result = [a add: b];
  [result print];
  printf ("\n");
  [a free];
  [b free];
  [result free];

  return 0;
}

输出结果:
(1/3) + (2/5) = (11/15)


Posing (扮演)和Categories(类目)的区别是:对于子类override父类方法的

情况,Categories 不能再调用父类的被重写的方法了;而Posing 可以通过“

[super 方法];”方式来调用父类被重写的方法。

0 0
原创粉丝点击