创建两个实例但输出保持不变

时间:2013-12-17 07:03:47

标签: objective-c

我是Objective C中的新手,我正在尝试运行本书中的一个示例,但两个实例的结果给出了相同的结果。这是代码:

#include <Foundation/Foundation.h>

//--- @interface section ---
@interface Fraction: NSObject
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int)d;
@end

//--- @implementation section ---
@implementation Fraction

int numerator;
int denominator;


-(void) print
{
   NSLog(@"%i/%i", numerator, denominator); 
}

-(void) setNumerator: (int) n
{
   numerator = n;   
}

-(void) setDenominator: (int) d
{
   denominator = d; 
}

@end

int main(int argc, const char * argv[])
{
    NSAutoreleasePool * fzrpool = [[NSAutoreleasePool alloc] init];

 Fraction *myFraction = [[Fraction alloc] init];
    [myFraction setNumerator: 1];
    [myFraction setDenominator: 5];

    Fraction *fzr = [[Fraction alloc] init];
    [fzr setNumerator: 3];
    [fzr setDenominator: 2];

    NSLog (@"The value of myFraction is: ");
    [myFraction print];
    NSLog (@"The value of fzr is: ");
    [fzr print];

    [fzrpool drain];
return 0;
}

输出

2013-12-17 11:56:01.187 helloworld[1988] The value of myFraction is:
2013-12-17 11:56:01.187 helloworld[1988] 3/2
2013-12-17 11:56:01.187 helloworld[1988] The value of fzr is:
2013-12-17 11:56:01.187 helloworld[1988] 3/2

我不能在这里使用@autoreleasepool {},因为我正在使用windows,gcc。我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

#include <Foundation/Foundation.h>

//--- @interface section ---
@interface Fraction: NSObject
{
    int numerator;
    int denominator;
}
-(void) print;
-(void) setNumerator: (int) n;
-(void) setDenominator: (int)d;
@end

//--- @implementation section ---
@implementation Fraction

-(void) print
{
    NSLog(@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
    numerator = n;
}

-(void) setDenominator: (int) d
{
    denominator = d;
}

@end

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

    Fraction *myFraction = [[Fraction alloc] init];
    [myFraction setNumerator: 1];
    [myFraction setDenominator: 5];

    Fraction *fzr = [[Fraction alloc] init];
    [fzr setNumerator: 3];
    [fzr setDenominator: 2];

    NSLog (@"The value of myFraction is: ");
    [myFraction print];
    NSLog (@"The value of fzr is: ");
    [fzr print];

    return 0;
}

答案 1 :(得分:0)

你的分子和分母都是全局的,因此最后一个值将持续存在。你希望它们都像ivar / property一样,所以需要将它们放在{和}

@implementation Fraction
{
int numerator;
int denominator;
}

当你在Windows中使用GCC时,

使用ints@interface移动上述块,然后就可以编译了。