从“Program 9.1”中的 Kochan 的“programing in Objective-c”中复制粘贴的练习代码。但它不编译。
有两类:分数和复数。Complex 的对象似乎工作正常,但“main.m”中的 Fraction 的对象“fracResult”给出了一个错误:“Assigning to “Fraction *” from in compatible type 'void'”。
这是分数.h:
#import <Foundation/Foundation.h>
// 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
分数.m 文件:
#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 NAN;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
// add a Fraction to the receiver
-(void) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c)) / (b * d)
numerator = numerator * f.denominator + denominator * f.numerator;
denominator = denominator * f.denominator;
}
-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while (v != 0) {
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
@end
main.m 文件:
#import "Fraction.h"
#import "Complex.h"
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *f1 = [[Fraction alloc] init];
Fraction *f2 = [[Fraction alloc] init];
Fraction *fracResult;
Complex *c1 = [[Complex alloc] init];
Complex *c2 = [[Complex alloc] init];
Complex *compResult;
[f1 setTo: 1 over: 10];
[f2 setTo: 2 over: 15];
[c1 setReal: 18.0 andImaginary: 2.5];
[c2 setReal: -5.0 andImaginary: 3.2];
// add and print 2 complex numbers
[c1 print]; NSLog (@" +"); [c2 print];
NSLog (@"---------");
compResult = [c1 add: c2];
[compResult print];
NSLog (@"\n");
[c1 release];
[c2 release];
[compResult release];
// add and print 2 fractions
[f1 print]; NSLog (@" +"); [f2 print];
NSLog (@"----");
fracResult= [f1 add: f2]; //this line gives an error
[fracResult print];
[f1 release];
[f2 release];
[fracResult release];
[pool drain];
return 0;
}
通过对这个主题的研究,我发现这种类型的错误通常是由于指针使用不当引起的。有人建议,简单地从方法“add:”的声明和实现中删除星号。但这导致了更多的“语义问题”
此外,有时书中的代码无法编译,因为书中使用的字符与 xcode 使用的字符不同。通常,破折号是不同的。但这也没有解决“不兼容类型”的问题。
欢迎任何意见或建议。