具有多个参数的方法

作者:追风剑情 发布于:2019-2-21 18:11 分类:Objective-C

示例:

Fraction.h

#import <Foundation/Foundation.h>

@interface Fraction : NSObject

//@property指令让编译器自动为numerator、denominator生成getter、setter方法
@property int numerator, denominator;

-(void) print;
+(int) printCallCount;
-(double) convertToNum;
-(void) setTo: (int) n over: (int) d;
-(void) set: (int) n : (int) d;
-(Fraction *) add: (Fraction *) f;
-(void) reduce;

@end


Fraction.m

#import "Fraction.h"

@implementation Fraction

@synthesize numerator, denominator;

// 统计所有对象调用print方法的次数,默认值为0
static int printCount;

// 静太方法
+(int) printCallCount
{
    return printCount;
}

-(void) print
{
    printCount++;
    //统计本实例对象调用print方法的次数,局部静态变量只会在方法第一次调用时初始化一次
    static int printCountIns = 0;
    printCountIns++;
    
    NSLog(@"%i/%i", numerator, denominator);
}

-(double) convertToNum
{
    if (denominator != 0)
        return (double) numerator / denominator;
    else
        return NAN;
}

// 多个参数的方法
-(void) setTo: (int) n over: (int) d
{
    numerator = n;
    denominator = d;
}

// 省略参数名的多个参数方法
// 注意,第一个参数名不能省
// 省略参数名不是一种好的编程风格,因为它使程序很难读懂并且很不直观,特别是参数很重要时。
-(void) set: (int) n : (int) d
{
    numerator = n;
    denominator = d;
}

// 分数相加
-(Fraction *) add: (Fraction *) f
{
    // 添加两个分数
    // a/b+c/d=((a*d)+(b*c))/(b*d)
    
    // 创建一个新对象来存储结果
    Fraction *result = [[Fraction alloc] init];
    result.numerator = numerator * f.denominator + denominator * f.numerator;
    result.denominator = denominator * f.denominator;
    
    // self关键字相当于C#的this
    // [self reduce];
    
    [result reduce];
    
    return result;
}

// 约分
-(void) reduce
{
    int u = numerator;
    int v = denominator;
    int temp;
    
    while (v != 0) {
        temp = u % v;
        u = v;
        v = temp;
    }
    
    numerator /= u;
    denominator /= u;
}

@end


main.m

#import <Foundation/Foundation.h>
#import "Fraction.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Fraction *aFraction = [[Fraction alloc] init];
        
        [aFraction setTo: 100 over: 200];
        [aFraction print];
        
        [aFraction setTo: 1 over: 3];
        [aFraction print];
        
        [aFraction set: 2 : 5];
        [aFraction print];
        
        Fraction *bFraction = [[Fraction alloc] init];
        [aFraction setTo: 1 over: 4];
        [bFraction setTo: 1 over: 2];
        
        [aFraction print];
        NSLog(@"+");
        [bFraction print];
        NSLog(@"=");
        
        Fraction *resultFraction = [aFraction add: bFraction];
        [resultFraction print];
        
        NSLog(@"Fraction print call count=%i", [Fraction printCallCount]);
    }
    return 0;
}


运行测试

111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号