类、对象和方法

作者:追风剑情 发布于:2019-2-19 17:25 分类:Objective-C

main.m

#import <Foundation/Foundation.h>

//分数类
//---- @interface 部分 ----
@interface Fraction: NSObject

-(void) print;
-(void) setNumberator: (int) n;
-(void) setDenominator: (int) d;
-(int) numerator;
-(int) denominator;

@end

//---- @implementation 部分 ----
@implementation Fraction
{
    int numerator;
    int denominator;
}
//- 定义实例方法 + 定义类方法
-(void) print
{
    NSLog(@"%i/%i", numerator, denominator);
}

//有参数的方法,冒号后面定义参数类型
-(void) setNumberator: (int) n
{
    numerator = n;
}

-(void) setDenominator: (int) d
{
    denominator = d;
}

//相当于C#的geter方法
-(int) numerator
{
    return numerator;
}

-(int) denominator
{
    return denominator;
}

@end

//---- program 部分 ----

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Fraction *myFraction;
        
        // 创建一个分数实例
        //myFraction = [Fraction alloc];//new一个实例
        //myFraction = [myFraction init];//初始化实例
        //上面两句代码的简写形式
        myFraction = [[Fraction alloc] init];
        
        // 设置分数为1/3
        [myFraction setNumberator: 1];
        [myFraction setDenominator: 3];
        
        // 使用打印方法显示分数
        NSLog(@"The value of myFaction is: ");
        [myFraction print];
        
        NSLog(@"The value of myFaction is: %i/%i",
              [myFraction numerator], [myFraction denominator]);
    }
    return 0;
}

运行测试

11111111111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号