现在的位置: 首页 > 综合 > 正文

objective-c 多态 — 动态类型 id 的使用

2013年09月21日 ⁄ 综合 ⁄ 共 755字 ⁄ 字号 评论关闭

转载于:http://www.cnblogs.com/54007/archive/2011/02/11/1951355.html

在C#中,我们用接口来实现多态。比如接口IOb,定义了1个方法F; 有两个类A,B都实现了IOb接口。

IOb item = new A();

item.F();//执行的是A.F();

item = new B();

item.F();//执行的B.F(); 

在objective-c中,interface 的含义和C#有了很大的不同,不能这样使用。

那么如何实现类似的效果呢。那就是特殊类型id,看如下代码段,注释:Fraction 和 Complex都包含print 方法。

 

#import “Fraction.h”
#import “Complex.h”
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id dataValue;//定义了一个id 类型变量
Fraction *f1 = [[Fraction alloc] init];
Complex *c1 = [[Complex alloc] init];
[f1 setTo: 2 over: 5];
[c1 setReal: 10.0 andImaginary: 2.5];
// first dataValue gets a fraction
dataValue = f1;
[dataValue print]; //调用Fraction的 print方法
// now dataValue gets a complex number
dataValue = c1;
[dataValue print]; //调用Complex的 print方法
[c1 release];
[f1 release];
[pool drain];
return 0;
}

抱歉!评论已关闭.