OC 結構體作為物件的屬性
// 結構體作為物件的屬性
#import <Foundation/Foundation.h>
/*
事物:學生
屬性:姓名生日
行為:可以說出自己姓名和生日
*/
typedefstruct{
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"
}
@end
int main(int argc, constchar * argv[]) {
Student *stu = [Studentnew];
stu->_name = @"wj";
//結構體只能在定義的時候初始化,但是在建立student類的物件的時候,已經初始化為0了,所以下面的程式碼會報錯
//stu->_birthday = {1991,08,18};
//可以通過加一個型別轉換來讓編譯器確定birthday是date型別,而不是陣列,如下
stu->
//本質是將一個值是{1991,8,18}的Date結構體拷貝一份給stu的birthday 即
//Date d = {1991,8,18};
//stu->_birthday = d;
//亦可以寫為
//stu->_birthday.year = 1991;
//stu->_birthday.month = 8;
//stu->_birthday.day = 18;
[stu say];
return 0;
}