天天看點

Objective-C執行個體方法之多個參數聲明與調用

類接口檔案(MathDiv.h)

#import <Foundation/Foundation.h>

//Define the Fraction class

@interface Fraction: NSObject

{

    int dividend;

    int divider;

}

@property int dividend, divider;

-(void) print;

-(void) setTo:(int)n over:(int)d;

-(double) convertToNum;

@end

類實作檔案(MathDiv.m)

#import "Fraction.h"

@implementation Fraction

@synthesize dividend, divider;

-(void) print

    NSLog (@"%i/%i", dividend, divider);

-(double) convertToNum

    if (divider != 0)

        return (double)dividend/divider;

    else

        return 0.0;

-(void) setTo:(int)n over: (int)d

    dividend = n;

    divider = d;

主程式調用

int main(int argc, const char * argv[])

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    Fraction *aFraction = [[Fraction alloc] init];

    [aFraction setTo: 100 over: 200];

    [aFraction print];

    [aFraction setTo: 1 over: 3];

    [aFraction release];

  [pool drain];

    return 0;

運作結果:

100/200

1/3

繼續閱讀