前面我们学习了方法的注意事项, 这次我们来自己练习一回~~~
需求: 比如, 我需要知道两个人的体重差值是多少, 用一个方法来实现, 看看下面的例子:
#import <Foundation/Foundation.h> @interface Preson : NSObject { @public double weight; } - (double)myWeight:(Preson *)p; @end @implementation Preson - (double)myWeight:(Preson *)p { return weight - p->weight; } @end int main() { Preson *zhangsan = [Preson new]; zhangsan->weight = 60.5; Preson *lisi = [Preson new]; lisi->weight = 50; double a = [zhangsan myWeight:lisi]; NSLog(@"他们之间相差%.2f/kg.", a); return 0; }
输出的结果是:
2015-01-15 13:46:39.589 a.out[10220:1073260] 他们之间相差10.50/kg.
这里解释一下方法里面的weight和p->weight, 其实weight就是zhangsan的weight, 而p->weight是lisi的weight, 之前我们也知道, 谁调用方法, 那么里面的成员就是谁, 而参数里的指针就是传入进去的, 在这里是zhangsan在调用, 而传入的是lisi的地址, 最后运算完再把值返回.
其实我们可以尝试把地址打印出来看看:
#import <Foundation/Foundation.h> @interface Preson : NSObject { @public double weight; } - (double)myWeight:(Preson *)p; @end @implementation Preson - (double)myWeight:(Preson *)p { NSLog(@"weight的地址:%p", &weight); NSLog(@"p->weight:%p", &p->weight); return weight - p->weight; } @end int main() { Preson *zhangsan = [Preson new]; zhangsan->weight = 60.5; NSLog(@"zhangsan体重的地址:%p", &zhangsan->weight); Preson *lisi = [Preson new]; lisi->weight = 50; NSLog(@"lisi体重的地址:%p", &lisi->weight); double a = [zhangsan myWeight:lisi]; NSLog(@"他们之间相差%.2f/kg", a); return 0; }
输出的结果:
2015-01-15 13:46:39.588 a.out[10220:1073260] zhangsan体重的地址:0x7ff0e840e068 2015-01-15 13:46:39.589 a.out[10220:1073260] lisi体重的地址:0x7ff0e8410c68 2015-01-15 13:46:39.589 a.out[10220:1073260] weight的地址:0x7ff0e840e068 2015-01-15 13:46:39.589 a.out[10220:1073260] p->weight:0x7ff0e8410c68 2015-01-15 13:46:39.589 a.out[10220:1073260] 他们之间相差10.50/kg
在这里, zhangsan的地址和weight的地址是一样的, 而p->weight的地址和lisi的地址是一样的.
好了, 这次我们就到这里, 大家也可以自己回去试试看, 下次我们继续~~