一 概述
给Car类设计一个方法,用来和其他车比较车速,如果本车速度快,就返回1;如果本车速度慢,就返回-1;速度相同就返回0
二 代码
复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include <Foundation/Foundation.h> @interface Car : NSObject { @public int speed; } -(int)compareSpeed:(Car *)otherCar; @end @implementation Car -(int)compareSpeed:(Car *)otherCar { return speed-(otherCar->speed); } @end int main() { Car *car1=[Car new]; car1->speed=300; Car *car2 = [Car new]; car2->speed=250; int result=[car1 compareSpeed:car2]; NSLog(@"两车比较的结果是:%d",result); return 0; } |
三 结果
- result的结果是50,说明第一辆车比第二辆车快