OC学习笔记,构造函数

构造函数用与在声明一个对象时候,为这个对象进行初始化。

默认构造函数是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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值