Sportica   Sportica

obj-c 定义一个类

//.h文件
#import <Foundation/Foundation.h>

@interface Fraction : NSObject    //定义一个新的类,里面有两个成员
{
    int numberator;
    int denominator;
}

-(void) print;             //定义打印输出
-(void) test_number;
-(void) setNumberator:(int)n;
-(void) setDenominator:(int)b;


@end



//.m文件中,具体实施
#import "testone.h"

@implementation Fraction

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

-(void) setNumberator:(int)n
{
    numberator = n;
}

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

-(void)test_number       //在别的文件中直接引用此方法。
{
    Fraction *fra1 = [[Fraction alloc]init];
    Fraction *fra2 = [[Fraction alloc]init];
    [fra1 setNumberator:2];
    [fra1 setDenominator:9];
    [fra1 print];
    
    [fra1 release];
    
}


@end


/**********************************/
//带多个参数时。重新写一个方法add。将一个分数与另一个分数相加,且把一个分数作为参数,下面为.h文件。

#import <Foundation/Foundation.h>

@interface Fraction : NSObject
{
    int numerator;
    int denominator;
}

@property int numerator,denominator;

-(void)print;
-(void)test_number;
-(void)add:(Fraction *)f;
-(void)setTo:(int)n over:(int)d;
-(double)convertToNum;

@end



//.m文件具体实施
#import <Foundation/Foundation.h>

@interface Fraction : NSObject
{
    int numerator;
    int denominator;
}

@property int numerator,denominator;

-(void)print;
-(void)test_number;   //main函数中直接调用此方法
-(void)add:(Fraction *)f;    //方法的参数为Fraction类,星号一定要带
-(void)setTo:(int)n over:(int)d;
-(double)convertToNum;

@end


/*输出结果:
   [3434:f803] 1/3
   [3434:f803] +
   [3434:f803] 1/2
   [3434:f803] =
   [3434:f803] 5/6
*/

 





posted @ 2012-06-28 16:13  qingjoin  阅读(345)  评论(0编辑  收藏  举报
  Sportica