"Program 9.1"의 Kochan에 의한 "objective-c에서 프로그래밍"에서 연습용 복사 붙여 넣기 코드. 그러나 컴파일되지 않습니다.오류 : 호환되지 않는 유형에서 할당 void
분수와 컴플렉스의 두 클래스가 있습니다. Complex의 오브젝트가 정상적으로 작동하지만 "main.m"의 Fraction 오브젝트 "fracResult"가 "Fraction *"과 호환되지 않는 유형 'void'에서 할당하는 중 오류가 발생합니다. "
#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
Fraction.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 파일 : 여기
이 Fraction.h입니다이 주제에 대한 연구함으로써#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에서 사용 된 문자의 차이로 인해 책의 코드가 컴파일되지 않는 경우가 있습니다. 종종 대시가 다릅니다. 그러나 그것도 "호환되지 않는 유형"으로 문제를 해결하지 못했습니다.
모든 조언이나 제안을 환영합니다.
수정 됨. 고맙습니다. –