8 动态绑定和id 类型 [Objective-C基础教程]

//*************************************************************************************//
#import "Fraction.h"
#import "Complex.h" // 两个类中都含有 print 方法
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Fraction *f = [[Fraction alloc] init];
Complex *c = [[Complex alloc] init];
id dataValue; // 声明 dataValue 为 id 类型
// 对对象的成员变量赋值
[f setTo: 2 over: 5];
[c setReal:10.0 andImaginary: 2.5];
dataValue = f; // 将 Fraction f 存储到 dataValue 中
[dataValue print]; // 现在 dataValue 可以调用用于 Fraction 对象的任何方法
dataValue = c; // 将 Complex c 存储到 dataValue 中
[dataValue print]; // 调用用于 Complex 对象的任何方法

// 问题:两次遇到 [dataValue print]; 并且 Fraction 和 Complex 类中都定义有 print 方法,系统如何知 道
调用哪个?
// 答案:在程序执行期间,当系统准备将 print 消息发送给 dataValue 时,它首先检查 dataValue 中存储
的对象所属的类。
[f release];
[c release];
[pool drain];
return 0;
}
//************************************************************************************//

 

来源://作者:/更新时间:2012-11-09
相关文章
评论:
验证码:
匿名评论:

最新文章

新热推荐

文章排行