博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Object-c 类的定义

Posted on 2011-11-01 15:47  zhangweia  阅读(3134)  评论(2编辑  收藏  举报

类定义文件:
 
#import <Foundation/Foundation.h>

//fraction :分数
@interface Fraction : NSObject
{//定义类得参数
    int numerator;    //分子
    int denominator;  //分母
}


-(void) print;
-(void) setNumerator:   (int)n;
-(void) setDenominator: (int)d;

-(int) getNumerator;
-(int) getDenominator;

@end
 
 
类实现文件:
#import "Fraction.h"

@implementation Fraction

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

-(void) print{
    NSLog(@"%i/%i",numerator,denominator);
}


-(void) setNumerator:(int)n
{
    numerator = n;
}

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

-(int)getNumerator
{
    return numerator;
}

-(int)getDenominator
{
    return denominator;
}
 
主实现文件:
 
int main (int argc, const char * argv[])
{

    // insert code here...
    //初始化类  
    Fraction *fraction = [[Fraction alloc]init];
    
    //调用类的方法
    [fraction setNumerator:1];
    [fraction setDenominator:3];
    [fraction print];
    
    int d = fraction.getDenominator;            
    return 0;
}