———–Java培训、Android培训、IOS培训、.Net培训、期待与您交流!————
本节是个人学习过程中的笔记,供初学者一起学习,欢迎大家批评指正,留言参与讨论,谢谢。
本节内容,OC多个参数方法,匿名类,自定义对象初始化方法,代码如下:
#import <Foundation/Foundation.h>
@interface Car : NSObject
{
@public
int speed;
char* brand;
}
-(Car*)initWithSpeed:(int)speed CarBrand:(char*)brand;
-(void)showCarInfo;
-(int)compareSpeedWithOtherCar:(Car*) anotherCar;//两个参数
-(int)getEqualSpeedWithFirstCar:(Car*)firstCar SecondCar:(Car*)secondCar;
//3个参数,求平均速度
@end
@implementation Car
-(Car*)initWithSpeed:(int)initSpeed CarBrand:(char*)initBrand //形参不能同名,否则就会覆盖
{
(self->speed) = initSpeed; //self可以省略
(self->brand) = initBrand;
return self;
}
//以下方式,测试成功
//-(Car*)initWithSpeed:(int)s CarBrand:(char*)b
//{
// speed = s;
// brand = b;
// return self;
//}
-(void)showCarInfo
{
NSLog(@"This %s's speed is %dkm/h!",brand,speed);
}
-(int)compareSpeedWithOtherCar:(Car *)anotherCar
{
[self showCarInfo];
[anotherCar showCarInfo];
int result = speed - anotherCar->speed;
NSLog(@"Speed compare result is %dkm/h!",result);
return result > 0 ? 1 :(result < 0 ? -1 : 0);
}
-(int)getEqualSpeedWithFirstCar:(Car*)firstCar SecondCar:(Car*)secondCar
{
[self showCarInfo];
[firstCar showCarInfo];
[secondCar showCarInfo];
int equal = (speed + firstCar->speed + secondCar->speed)/3;
NSLog(@"These three cars'equal speed is %dkm/h!",equal);
return equal;
}
@end
void testCar()
{
Car* bmw = [Car new];
bmw->speed = 200;
bmw->brand ="BMW";
Car* benz = [Car new];
benz->speed = 220;
benz->brand ="BENZ";
Car* moto = [Car new];
moto->speed = 120;
moto->brand ="DaYangMOTO";
Car* sanlun = [Car new];
sanlun->speed = 60;
sanlun->brand ="FengHuangSanLun";
[bmw compareSpeedWithOtherCar: benz];
[bmw getEqualSpeedWithFirstCar: benz SecondCar: sanlun];
//这种方式傻傻的
// Car* taxis[] = {[Car new],[Car new],[Car new]};
// Car* hunda = taxis[0];
// hunda->speed = 200;
// hunda->brand ="HUNDA";
// [hunda showCarInfo];
}
void testAnonymityClass()
{
[[Car new] showCarInfo];
[[[Car new] initWithSpeed:80 CarBrand:"Anony"] showCarInfo];
//匿名的结果,就是没有指针指向这个对象,只能进行一次性操作,就如路人甲碰面不再出现
}
void testInit()
{
Car* tianlai = [Car new];
[tianlai initWithSpeed:150 CarBrand:"TianLai"];
[tianlai showCarInfo];
//一句话完成对象创建和初始化
Car* suv = [[Car new] initWithSpeed:250 CarBrand:"SUV"];
[suv showCarInfo];
[suv compareSpeedWithOtherCar: tianlai];
}
int main()
{
testCar();
testAnonymityClass();
testInit();
return 0;
}
程序运行结果如下: