构造函数用与在声明一个对象时候,为这个对象进行初始化。
默认构造函数是init。
也可以自定义构造函数,通常规定已init开头。
@interface Person : NSObject {
@private
// 把_age _name包装起来,外部不能使用
// 确保了安全性
// 字段field 成员变量
int _age;
NSString *_name;
}
// 向外面暴露的成员方法
// setAge:和setAge这2个方法是我们对_age字段提供的2个函数。
// 构造函数
- (id) init;
- (id) initWithName:(NSString *)newName;
- (id) initWithName:(NSString *)newName withAge:(int)newAge;
- (void) setAge:(int)newAge;
- (int) getAge;
- (void) setName:(NSString *)newName;
- (NSString *) getName;
- (void) setName:(NSString *)newName withAge:(int)newAge;
@end
上面.h文件中 init 和 initWithName: 以及 initWithName:withAge:都是构造函数。
分别是无参,一个参数,两个参数。
在.m文件中对这些函数进行实现。
@implementation Person
- (id) init {
return [self initWithName:@"无名氏"];
}
- (id) initWithName:(NSString *)newName {
return [self initWithName:newName withAge:-1];
}
// 构造函数实现部分只写一次,其他方法相互调用
- (id) initWithName:(NSString *)newName withAge:(int)newAge {
self = [super init];
if (self) {
[self setName:newName withAge:newAge];
NSLog(@"在构造函数中 name %@ age %d %s", _name, _age, __FUNCTION__);
}
return self;
}
- (void) setAge:(int)newAge{
_age = newAge;
}
- (int) getAge{
return _age;
}
- (void) setName:(NSString *)newName {
_name = newName;
}
- (NSString *) getName {
return _name;
}
- (void) setName:(NSString *)newName withAge:(int)newAge {
[self setName:newName];
[self setAge:newAge];
}
@end
在main函数中声明创建对象即可。
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *xiaoming = [[Person alloc] init];
[xiaoming setAge:20];
[xiaoming setName:@"小明"];
Person *xiaoli = [[Person alloc] init];
[xiaoli setName:@"小李" withAge:30];
Person *xiaozhang = [[Person alloc] initWithName:@"小张" withAge:50];
}
return 0;
}