// // main.m // 结构体作为对象的属性 #import <Foundation/Foundation.h> typedef struct { int year; int month; int day; } Date; @interface Student : NSObject { @public NSString *_name; // struct Date birthday; 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];//结构体里面的值都是0 stu->_name = @"lnj"; // 1.结构体只能在定义的时候初始化 // 2.系统并不清楚它是数组还是结构体 //初始化结构体属性 //方法一:强制转换 stu->_birthday = (Date){1986, 1, 15};//大括号有可能是数组, //方法二:定义一个新的结构体,给d赋值,将d赋值给_birthday Date d = {1986, 1, 15}; stu->_birthday = d; //方法三:分别赋值 stu->_birthday.year = 1986; stu->_birthday.month = 1; stu->_birthday.day = 15; // 3.让学生说出自己的姓名和生日 [stu say]; Date d1 = {1999, 1, 5}; Date d2; d2 = d1; // 本质是将d1所有的属性的值都拷贝了一份赋值给d;不是传递地址 d2.year = 2000; printf("d1 = year = %i ", d1.year);//1999 printf("d2 = year = %i ", d2.year);//2000 return 0; }