且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Objective-C实例方法之多个参数声明与调用

更新时间:2022-06-08 11:44:35

类接口文件(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;
}
 
@end

 

主程序调用

#import "Fraction.h"
 
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 print];
    
    [aFraction release];
  [pool drain];
    
    return 0;
}

 

运行结果:

100/200

1/3