0

这是(用户)micmoo 对类和实例方法有什么区别的回应的后续问题?.

如果我将变量 numberOfPeople 从静态更改为类中的局部变量,我会得到 numberOfPeople 为 0。我还添加了一行来显示 numberOfPeople 变量每次递增后的值。为避免混淆,我的代码如下:

// Diffrentiating between class method and instance method

#import <Foundation/Foundation.h>


// static int numberOfPeople = 0;

@interface MNPerson : NSObject {
    int age;  //instance variable
    int numberOfPeople;
}

+ (int)population; //class method. Returns how many people have been made.
- (id)init; //instance. Constructs object, increments numberOfPeople by one.
- (int)age; //instance. returns the person age
@end

@implementation MNPerson

int numberOfPeople = 0; 
- (id)init{

    if (self = [super init]){
        numberOfPeople++;
        NSLog(@"Number of people = %i", numberOfPeople);
        age = 0;
    }    
    return self;
}

+ (int)population{ 
    return numberOfPeople;
}

- (int)age{
    return age;
}

@end

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


    MNPerson *micmoo = [[MNPerson alloc] init];
    MNPerson *jon = [[MNPerson alloc] init];
    NSLog(@"Age: %d",[micmoo age]);
    NSLog(@"Number Of people: %d",[MNPerson population]);
}

}

输出:

在初始化块中。人数 = 1 在初始化块中。人数 = 1 年龄:0 人数:0

案例 2:如果您将实现中的 numberOfPeople 更改为 5(比如说)。输出仍然没有意义。

预先感谢您的帮助。

4

1 回答 1

2

numberOfPeople您正在隐藏使用实例级别声明的全局变量numberOfPeople。将其中一个名称更改为其他名称以避免此问题

于 2012-08-09T17:10:12.560 回答