首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

+号级别得成员方法兑现

2012-08-22 
+号级别得成员方法实现Demo:加号级别的成员方法的实现:#import Foundation/Foundation.h@interface Pers

+号级别得成员方法实现

Demo:加号级别的成员方法的实现:

#import <Foundation/Foundation.h>

@interface Person:NSObject

{

????? int _age;

}

-(id)initWithAge:(int)age;

+(id)personWithAge:(int)age;

-(void)print;

@end

?

@implementation Person

?

-(id)initWithAge:(int)age

{

????? self = [super init];

????? if (nil != self) {

???????? _age = age;

????? }

????? return self;

}

+(id)personWithAge:(int)age

{??? //返回id类型和用到self是为子类考虑,子类继承Person,当调用该方法是返回的是子类的对象

????? //在+级别的方法中,一般用self

????? id obj = [[self alloc] initWithAge:age];

????? return [obj autorelease];

?????

}

-(void)print

{

????? NSLog(@"age = %d",_age );

}

@end

?

@interface Student : Person

@end

?

@implementation Student

@end

?

?

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

??? NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

?????

????? Person* p = [Person personWithAge:20];

????? [p print];

?????

????? Student* stu = [Student personWithAge:30];

????? NSLog(@"%@", NSStringFromClass([stu class]));

????? [stu print];

??

??? [pool drain];

??? return 0;

}

?

热点排行