我对以下代码有疑问。输出错误:frac1
应打印出来" 2/3",而是将其覆盖到" 3/7"。我似乎无法弄清楚为什么会被覆盖。
#import <Foundation/Foundation.h>
// ---- INTERFACE -----
@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
// ---------- EXECUTION--------
int main (int argc, char * argv[])
{
@autoreleasepool {
Fraction * frac1 = [[Fraction alloc]init];
Fraction * frac2 = [[Fraction alloc]init];
[frac1 setNumerator:2];
[frac1 setDenominator:3];
// set second fraction
[frac2 setNumerator:3];
[frac2 setDenominator:7];
NSLog(@"this is the value of frac1:");
[frac1 print];
NSLog(@"this is the value of frac2:");
[frac2 print];
}
return 0;
}
答案 0 :(得分:3)
问题是numerator
和denominator
被设置为全局变量,而不是实例变量。为了使实例变量将它们作为@implementation定义的一部分包含在{}中。
修正:
@implementation Fraction {
int numerator;
int denominator;
}
输出:
这是frac1的价值:
2/3
这是frac2的价值:
3/7
答案 1 :(得分:2)
使用此代码:
@interface Fraction : NSObject
@property (assign, nonatomic) int numerator;
@property (assign, nonatomic) int denominator;
- (void)print;
@end
@implementation Fraction
- (void)setNumerator:(int)numerator {
if (_numerator != numerator) {
_numerator = numerator;
}
}
- (void)setDenominator:(int)denominator {
if (_denominator != denominator) {
_denominator = denominator;
}
}
-(void) print{
NSLog(@"%i/%i", _numerator, _denominator);
}
@end
// OUTPUT
2015-01-18 18:12:58.844 fraction[29486:2733137] this is the value of frac1:
2015-01-18 18:12:58.845 fraction[29486:2733137] 2/3
2015-01-18 18:12:58.846 fraction[29486:2733137] this is the value of frac2:
2015-01-18 18:12:58.846 fraction[29486:2733137] 3/7
在你的情况下,int numerator;分母;是全局变量,而不是对象属性。