2012年5月21日 星期一

Dynamic Binding and the id Type

refer to Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009)

#import “ Fraction.h ”
#import “ Complex.h ”
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
id    dataValue; //注意沒有 " * "
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;  // Dynamic Binding first
[dataValue print];
// now dataValue gets a complex number
dataValue = c1;   // Dynamic Binding second
[dataValue print];
[c1 release];
[f1 release];
[pool drain];
return 0;
}

沒有留言: