OC 中多引數方法宣告
阿新 • • 發佈:2019-01-09
#import <Foundation/Foundation.h> @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:方法定義
5:多引數方法定義
6:匿名物件
[[Car new]run]; //程式不會執行錯誤,但是會產生記憶體洩漏;
[Car new]->speed=100; //返回值將是0,因為每次都新建了一個Car物件.而speed的初始值為0;
#import <Foundation/Foundation.h> @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]; }