【发布时间】:2017-08-16 02:18:01
【问题描述】:
假设我在 Objective-C 中创建了一个 Fraction 类(如“使用 Objective-C 编程”一书)。其中一个方法 add: 最初是这样创建的:
//Fraction.h & most of Fraction.m left out for brevity's sake.
-(Fraction *)add: (Fraction*) f {
Fraction *result = [[Fraction alloc] init];
//Notice the dot-notation for the f-Fraction
result.numerator = numerator * f.denominator + denominator * f.numerator;
result.denominator = denominator * f.denominator;
return result;
}
然后在后面的一个练习中,它说将返回类型和参数类型更改为 id 并使其工作。如上所示的点符号不再起作用,所以我将其更改为:
-(id)add: (id)f {
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * [f denominator] + denominator * [f numerator];
// So forth and so on...
return result;
}
现在我猜测为什么需要更改点表示法是因为直到运行时,程序不知道传递给添加参数(f)的对象类型,因此编译器不知道'不知道 f 的任何访问器方法。
我是否接近理解这一点?如果不是,有人可以澄清一下吗?
【问题讨论】:
-
即使您可以将
id f类型转换为Fraction 并使用.
标签: objective-c syntax