黑马程序员—OC学习笔记—多个参数方法,匿名类,自定义对象初始化方法

———–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;
}

程序运行结果如下:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值