在我正在阅读的书中,他解释了如何在主文件中创建类别,但我试图弄清楚如何在单独的文件中执行此操作..
我想为 Fraction 类创建一个名为“MathOperations”的类别,因此我打开了一个名为 Fraction+MathOperations 的新 .h 和 .m,因为我知道这是惯例。
这是分数.h
#import "Fraction.h"
@interface Fraction : NSObject
@property int numerator, denumerator;
-(void) print: (BOOL) test;
-(void) setTo: (int) n over: (int) d;
-(void) reduce;
-(double) convertToNum;
-(id) addFrac:(id)f;
-(void) justPrint;
-(id) initWith:(int)n over:(int)f;
+(Fraction *) allocF;
+(int) count;
+(int) gCounter;
@end
分数+数学运算.h
#import "Fraction.h"
@interface Fraction (MathOperations)
-(Fraction *) add: (Fraction *) f;
-(Fraction *) substract: (Fraction *) f;
-(Fraction *) multiply: (Fraction *) f;
-(Fraction *) divide: (Fraction *) f;
@end
分数+数学运算.m
#import "Fraction.h"
@implementation Fraction (MathOperations)
-(Fraction *)add:(Fraction *)f
{
extern int gCounter;
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denumerator + denumerator * f.numerator;
result.denumerator = denumerator * f.denumerator;
[result reduce];
++gCounter;
return result;
}
-(Fraction *)substract:(Fraction *)f
{
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denumerator - denumerator * f.numerator;
result.denumerator = denumerator * f.denumerator;
//[result reduce];
return result;
}
-(Fraction *)multiply:(Fraction *)f
{
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.numerator;
result.denumerator = denumerator * f.denumerator;
//[result reduce];
return result;
}
-(Fraction *)divide:(Fraction *)f
{
Fraction *result = [[Fraction alloc] init];
result.numerator = numerator * f.denumerator;
result.denumerator = denumerator * f.numerator;
//[result reduce];
return result;
}
@end
显然,我声明了一些错误,因为我得到了一堆未声明变量的错误。此外,在原始 Fraction 类中声明新接口和实现是否更合理?
错误:
在 Fraction 类中,我有一些名为“numerator”和“denumerator”的属性,它们似乎没有在 meth 实现文件 tnx 中声明