我收到以下错误:
"warning: conflicting types for '-(Fraction *) add: (Fraction *) f;"
行:
-(Fraction *) add: (Fraction *) f;
这是我的标题代码:
// Define the Fraction class
@interface Fraction : NSObject {
int numerator;
int denominator;
}
@property int numerator, denominator;
-(void) print;
-(void) setTo: (int) n over: (int) d;
-(double) convertToNum;
-(void) add: (Fraction *) f;
-(void) reduce;
@end
Here is my .m code:
#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print
{
NSLog (@"%i / %i", numerator, denominator);
}
-(double) convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
else
return 1.0;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
-(Fraction *) add: (Fraction *) f;
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c)) / (b *d)
// multiply the denominators
// then mulitply each numerator by the OPPOSITE
// denominator
// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;
resultNum = numerator * f.denominator + denominator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo: resultNum over: resultDenom];
NSLog(@"%i, %i", resultNum, resultDenom);
[result reduce]; // reduces the numerator and denominator
// as both are instance (classwide) variables
NSLog(@"%i is the result", result);
return result;
}
@end
答案 0 :(得分:4)
你有两种不同的add实现:一个是:
-(void) add: (Fraction *) f;
界面内的(.h文件)。另一个是在实现(.m文件)
中-(Fraction *) add: (Fraction *) f;
您需要更改标题以读取后一个声明,以便它返回一个Fraction指针,而不是void。
答案 1 :(得分:3)
那是因为在你的头文件中,你已经将返回类型声明为void:
-(void) add: (Fraction *) f;
然而,在您的实现中,您实现了返回Fraction指针的方法:
-(Fraction *) add: (Fraction *)
此外,您的实现中有分号,可能只是复制粘贴错误?
答案 2 :(得分:1)
您声明add
方法在您的界面中返回void
,但您的实现返回Fraction *