黑马程序员技术交流社区

标题: *****应用:创建一个学生类初始化年龄 [打印本页]

作者: Storm_    时间: 2015-11-7 19:12
标题: *****应用:创建一个学生类初始化年龄

创建一个学生类Student ,通过重写构造方法实现创建学生对象的时候 默认的年龄值指定的年龄


Student.h文件

#import <Foundation/Foundation.h>
#import "Person.h"

@interface Student : NSObject
@property(nonatomic,assign) int age;
-(instancetype)initWithAge:(int)age;
+(instancetype)studentWithAge:(int)age;
@end


Student.m文件

#import "Student.h"

@implementation Student

-(void)dealloc{
    NSLog(@"s dealloc");
    [super dealloc];
}
-(instancetype)initWithAge:(int)age{
    //1 先初始化父类,并且判断是否初始化成功
    if (self = [super init]) {
        //初始化子类
        _age =age;
    }
    //返回self
    return  self;
}
+(instancetype)studentWithAge:(int)age{
    return [[[self alloc] initWithAge:age] autorelease];
}
@end


main.m文件

#import <Foundation/Foundation.h>
#import "Student.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Student *s = [[Student alloc]initWithAge:18];
        NSLog(@"%d",s.age);
        [s release];
   
   
    //快速的创建Student对象,并且初始化年龄
    //1)定义类方法
    //2)类方法有参数,传递一个年龄
    Student *s2 =   [Student  studentWithAge:20];
    NSLog(@"%d",s2.age);
    }
    return 0;
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2