结构体作为对象的属性

typedef struct {
    int year;
    int month;
    int day;
} Date;

@interface Student : NSObject
{
    @public
    NSString *_name;
    Date _birthday;
}

- (void)say;

@end


@implementation Student

- (void)say
{
    NSLog(@"name = %@, year = %d, month = %d, day = %d", _name, _birthday.year, _birthday.month, _birthday.day);
}

@end

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

    // 创建学生对象
    // 1开辟存储空间, 2初始化属性, 3返回地址
    Student *stu = [Student new];

    // 2 设置学生对象的属性
    stu->_name = @"lnj";
    // 1.结构体只能定义的时候初始化
    // 2. 系统并不清楚它是数组还是结构体

    // 初始化结构体的属性
    // 方法一: 强制转换
    stu->_birthday = (Date){1986, 1, 15};

    // 方法二: 定义一个新的结构体 给d赋值 将d赋值给_birtyday
    Date d = {1986, 1, 15};
    stu->_birthday = d;

    // 方法三: 分别赋值
    stu->_birthday.year = 1986;
    stu->_birthday.month = 1;
    stu->_birthday.day = 15;

    // 3.让学生说出自己的姓名和生日
    [stu say];

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值