您的位置:首页 > 其它

构造方法

2016-06-09 16:22 288 查看
1:使用构造方法的目的:为了让对象方法一构建出来,成员变量就拥有固定的值

2:先调用父类的构造方法再进行子类子类内部成员变量的初始化

#import<Foundation/Foundation.h>
@interface Person:NSObject
@property int age;
@end
@implementation Person
//如果想让person对象的age的初始值为10
-(id)init
{
//初始化对象拥有的父类成员变量
if(self=[super init])
{
//初始化对象自身的成员变量
_age=10;
}
//返回一个已经初始化完成的对象
return self;
}
@end
int main()
{
// Person *p =[Person new];
/*
new方法内部所做的事情
1:分配内存给对象 +alloc
Person *p1=[Person alloc];
2:初始化对象 -init
Person *p =[p1 init];
以上两个过程合成为一句
Person *p =[[Person alloc]init];
*/
Person *p =[[Person alloc]init];
NSLog(@"年龄为%i",p.age);
return 0;
}

如果让student 继承person类,age的初始值为10,学号为0111;

#import<Foundation/Foundation.h>
@interface Person:NSObject
@property int age;
@end
@implementation Person
//如果想让person对象的age的初始值为10
-(id)init
{
//初始化对象拥有的父类成员变量
if(self=[super init])
{
//初始化对象自身的成员变量
_age=10;
}
//返回一个已经初始化完成的对象
return self;
}
@end
@interface Student : Person
@property int no;
@end
@implementation Student
-(id)init
{
if(self=[super init])
{
_no=0111;
}
return self;
}
@end
int main()
{
// Person *p =[Person new];
/*
new方法内部所做的事情
1:分配内存给对象 +alloc
Person *p1=[Person alloc];
2:初始化对象 -init
Person *p =[p1 init];
以上两个过程合成为一句
Person *p =[[Person alloc]init];
*/
//    Person *p =[[Person alloc]init];
//    NSLog(@"年龄为%i",p.age);
Student *s = [[Student alloc]init];
NSLog(@"年龄:%i 学号:%i",s.age,s.no);

return 0;
}
运行结果为:



3:自定义构造方法:

/*

规范:

返回值为id 类型

方法名都是以init方法开头

*/

#import<Foundation/Foundation.h>
@interface Person:NSObject
@property int age;
@end
@implementation Person
//如果想让person对象的age的初始值为10
-(id)init
{
//初始化对象拥有的父类成员变量
if(self=[super init])
{
//初始化对象自身的成员变量
_age=10;
}
//返回一个已经初始化完成的对象
return self;
}
@end
@interface Student : Person
@property(nonatomic,strong) NSString *no;
-(id)initWithAge:(int)age andNo:(NSString *)no;
@end
@implementation Student
-(id)initWithAge:(int)age andNo:(NSString *)no
{
if(self = [super init])
{
_no = no;
}
return self;
}
@end
int main()
{
// Person *p =[Person new];
/*
new方法内部所做的事情
1:分配内存给对象 +alloc
Person *p1=[Person alloc];
2:初始化对象 -init
Person *p =[p1 init];
以上两个过程合成为一句
Person *p =[[Person alloc]init];
*/
//    Person *p =[[Person alloc]init];
//    NSLog(@"年龄为%i",p.age);
Student *s = [[Student alloc]init];
s.age = 20;
s.no = @"bairong";
NSLog(@"年龄:%i 学号:%@",s.age,s.no);
return 0;
}
运行结果为;

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: