如果要使用分数作为参数传递到add方法中,这里必须使用指针“*”,不使用就错了。
正确使用:
-(void) add: (Fraction *) f;
错误的使用:
-(void) add: (Fraction ) f;
公约数代码注意不要把赋值过程放到花括号内部。
-(void) reduce
{
int u = numberator;
int v = denominator;
int temp;
while(v != 0)
{
temp = u % v;
u = v;
v =temp;
}
numberator /= u;
denominator /= u;
NSLog(@"公约数为:%i",u);
}
可以发送消息给当前对象来调用函数:
[self reduce];
-(Fraction*) addAndReturnPoint:(Fraction *) f
{
//a/b + c/d = (ad + bc)/bd;
Fraction *result = [[Fraction alloc] init];
result.numberator = numberator * f.denominator + denominator * f.numberator;
result.denominator = denominator * f.denominator;
[result reduce];
return result;
}
Fraction *aFraction = [[Fraction alloc]init];
Fraction *bFraction = [[Fraction alloc]init];
Fraction *cFraction;
[aFraction setTo:1 over:4];
[bFraction setTo:1 over:2];
[aFraction print];
NSLog(@"+");
[bFraction print];
NSLog(@"=");
cFraction = [aFraction addAndReturnPoint:bFraction];
[cFraction print];
cFraction并没有实例化,而是通过函数 addAndReturnPoint 的返回Fraction对象来赋值。
子类中使用实例变量,必须先在接口部分声明和合成(synthesize)的变量时私有的,子类中不能直接访问,需要明确定义或合成取值的方法才能访问实例变量。
int main(int argc, const char * argv[]) {
@autoreleasepool {
ClassB *cb = [[ClassB alloc] init];
[cb initVra];
[cb printVra];
}
return 0;
}
注意:其中ClassB并没有定义方法initVra,这个方法就是继承的父类ClassA中的方法。类似alloc和init都是你使用了但是并没有定义的方法,这些方法继承与NSObject类。如果定义一个ClassC继承ClassB,那么ClassC的实例任然可以调用ClassA中的方法initVar。这是继承的形象描述。
像对象发送消息时。首先,检查该对象所属的类,查看在类中是否明确定义了一个具有指定名称的方法。如果有定义,就会使用这种方法。如果没有定义,就会检查他的父类。如果父类中有定义,就使用了这个方法。否则,继续寻找,知道两种情况中的一种才会停止:1,发现包含指定方法的类;2,搜索到根类也没有发现任何方法。这时会报错。
但是父类是不能直接调用仅仅定义在子类中的方法的,相反,子类是可以直接调用父类中的方法的。