由之前範例延伸學習
- Fraction.h
... -(void) setNumerator: (int) n andDenominator: (int) p1; ...
- Fraction.m
... -(void) setNumerator: (int) n andDenominator: (int) p1 { numerator = n; denominator = p1; } ...
- main.m
#import <stdio.h> #import "Fraction.h" int main( int argc, const char *argv[] ) { // create a new instance Fraction *frac = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; // set the values [frac setNumerator: 5]; [frac setDenominator: 10]; // combined set [frac2 setNumerator: 5 andDenominator: 10]; // print it printf( "The fraction is: " ); [frac print]; printf( "\n" ); // print it printf( "Fraction 2 is: " ); [frac2 print]; printf( "\n" ); // free memory [frac release]; [frac2 release]; return 0; }
- output
The fraction is: 5/10 = 0.500000 Fraction 2 is: 5/10 = 0.500000
- 這個 method 實際上叫做 setNumerator:OtherParameter1:
- 加入其他參數的方法就跟加入第二個時一樣,即 method:label1:label2:label3: ,而呼叫的方法是 [obj method: param1 label1: param2 label2: param3 label3: param4]
- Labels 是非必要的,所以可以有一個像這樣的 method:method:::,簡單的省略 label 名稱,但以 : 區隔參數。並不建議這樣使用。
沒有留言:
張貼留言