OC 中多参数方法声明

#import 

@interface Calculator : NSObject
{
    @public
    int number;
}
-(double)pi;  //返回 PI 的值
//一个方法名对应一个冒号,冒号也是方法的一部分
-(double)pingfang:(double)number;  //实现计算器的平方运算
-(double)SumOfnum:(double)num1 andNum2:(double)num2;  //实现计算器的加法运算

@end
@implementation Calculator
-(double)pi;
{
    return 3.1415926;
}
-(double)pingfang:(double)number;
{
    return number * number;
}
-(double)SumOfnum:(double)num1 andNum2:(double)num2
{
    return num1 + num2;
}
@end
int main(int argc,char *argv[])
{
    Calculator *c =[ Calculator new];
    NSLog(@"pi的值为:%f",[c pi]);
    c->number = 2;
    NSLog(@"%i的平方为%f",c->number,[c pingfang:c->number]);
    NSLog(@"两个数的和为%f",[c SumOfnum:2 andNum2:3]);
}

注意:

      1:OC中不存在方法重载,如果两个方法的方法名重复,程序将报错

@implementation Calculator
-(double)pi;
{
    return 3.1415926;
}
-(double)pi;
{
    return 3.14;
}

-(double)pingfang:(double)number;
{
    return number * number;
}
-(double)SumOfnum:(double)num1 andNum2:(double)num2
{
    return num1 + num2;
}
@end

    

  2:-(double)pi;

     -(double)pi:(int)a;是两个不同的方法

  3:同一个类中不允许两个对象方法同名

  4:方法定义

  OC 中多参数方法声明_第1张图片

 5:多参数方法定义

OC 中多参数方法声明_第2张图片

6:匿名对象     

[[Car newrun;  //程序不会运行错误,但是会产生内存泄漏;

Car new]->speed=100; //返回值将是0,因为每次都新建了一个Car对象.而speed的初始值为0;

#import 
@interface Car:NSObject
{
    
    @public
    int speed;
}
-(void)run;
@end
@implementation Car

-(void)run
{
    NSLog(@"速度为%i的车子跑起来了",speed);
}

@end
int main()
{
//    Car *car = [Car new];
//    car->speed=100;
    [Car new]->speed=100;
    [[Car new]run];
    
}


你可能感兴趣的:(Objective-C)