0

有人可以告诉我以下程序有什么问题吗

#import <Foundation/Foundation.h>

@interface Fraction:NSObject

-(void)getNumerator: (int) numerator;
-(void)getDenominator: (int) denominator;
-(int) calculate;

@end


@implementation Fraction
{
    int num;
    int den;
    int result;
}

-(void) getDenominator:(int)denominator{
    den=denominator;

}

-(void) getNumerator:(int)numerator{
    num=numerator;
}

-(void) calculate{
    result = num/den;
    NSLog(@"%i",result);
    //return result;
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        Fraction *myFrac;
        // insert code here...
        myFrac = [Fraction alloc];
        myFrac = [Fraction init];
        [myFrac getNumerator:4];
        [myFrac getDenominator:6];
[myFrac calculate];
//        NSLog(@"the result is %i",result);
        NSLog(@"Hello, World!");


    }
    return 0;
}

我不断收到此错误:

roject3[523:303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[Fraction<0x100001200> init]: cannot init a class object.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff8a01641c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff824d5e75 objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff8a019650 +[NSObject(NSObject) dealloc] + 0
    3   project3                            0x0000000100000e0c main + 108
    4   libdyld.dylib                       0x00007fff826b35fd start + 1
    5   ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

为什么我不能实例化一个类对象

4

2 回答 2

2

改变这个:

myFrac = [Fraction alloc];
myFrac = [Fraction init];

对此:

myFrac = [[Fraction alloc] init];

如果您不想嵌套,我认为您需要这样做:

myFrac = [Fraction alloc];
myFrac = [myFrac init];

但最好只做嵌套。虽然,只要Fraction是自定义类,您就应该创建自己的factory method. ;)

此外,您的get方法实际上应该称为set方法(或者更好的是,使用@properties)。

于 2013-11-05T02:50:18.363 回答
2
myFrac = [Fraction alloc];
myFrac = [Fraction init];

没有意义,应该是

myFrac = [[Fraction alloc] init];
于 2013-11-05T02:50:29.723 回答