天天看点

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