1

有人可以向我描述以下代码(objective-C)中的实例/对象是什么。我很困惑,因为 void 之前的 (-) void 意味着它是一个实例的方法,但我不知道实例/对象在哪里。

  #import <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
//program section
int main(int argc, const char * argv[])
{
//this is a program to work with fractions-class version
    @autoreleasepool {
        Fraction *myFraction;
        //create an instance of a fraction
        myFraction = [Fraction alloc];
        myFraction = [myFraction init];
        //set fraction to 1/3
        [myFraction setNumerator:1];
        [myFraction setDenominator:3];
        //display the fraction via print methoD


        NSLog(@"the value of myFraction is:");
        [myFraction print];
         }
    return 0;
}
4

1 回答 1

1

myFraction 是 Fraction 类的实例。实例方法必须针对实例而不是类,如您所见,print、setNumerator 和 setDenominator 都针对 myFraction。

于 2013-02-15T04:30:44.137 回答