OC 结构体作为对象的属性


//  结构体作为对象的属性

#import <Foundation/Foundation.h>

/*

 事物:学生

 属性:姓名 生日

 行为:可以说出自己姓名和生日

 */

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 = %i, month = %i, day = %i",_name,_birthday.year,_birthday.month,_birthday.day);

}


@end

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

    Student *stu = [Student new];

    stu->_name = @"wj";

    //结构体只能在定义的时候初始化,但是在创建student类的对象的时候,已经初始化为0了,所以下面的代码会报错

    //stu->_birthday = {1991,08,18};

    //可以通过加一个类型转换来让编译器确定birthdaydate类型,而不是数组,如下

    stu->_birthday = (Date){1991,8,18};

    //本质是将一个值是{1991,8,18}Date结构体拷贝一份给stubirthday

    //Date d = {1991,8,18};

    //stu->_birthday = d;

    //亦可以写为

    //stu->_birthday.year = 1991;

    //stu->_birthday.month = 8;

    //stu->_birthday.day = 18;

    

    [stu say];

    return 0;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值