1. 程式人生 > >Object C學習筆記20-結構體(轉)

Object C學習筆記20-結構體(轉)

  在學習Object C中的過程中,關於struct的資料貌似非常少,查閱了C方面的資料總結了一些學習心得!

 

一. 定義結構

    結構體是一種資料型別的組合和資料抽象。結構體的定義語法如下:

    struct 結構體名稱

    {

      型別 變數名;

      型別 變數名;

    }

    例項程式碼如下:

struct student {
    char* name;
    enum sex sex;
    int age;
};

  上面程式碼定義了一個結構體student,其中有三個變數name,sex,age ,其中sex是一個列舉。student是一個識別符號,也稱為tag.

 

  二. 定義結構變數

    結構變數定義程式碼如下:

 

struct student {
            char* name;
            enum sex sex;
            int age;
}stu1,stu2;

    以上定義了 兩個student 型別的結構變數stu1,stu2;

    或者使用如下方式定義變數

struct student a={"aaa",34};
struct student b={"cccc",45};

  三. 如何在類中使用結構

    先定義一個類Person,其中有兩個屬性為列舉和結構體

enum sex{
    male=0,
    female=1
};

struct student {
    char* name;
    int age;
};

#import <Foundation/Foundation.h>

@interface Person : NSObject{
    enum sex sex;
    struct student stu;
}

@property (nonatomic,assign) enum sex sex;
@property (nonatomic,assign) struct
student stu; -(void) write; @end --------------------------------------------------------- #import "Person.h" @implementation Person @synthesize sex; @synthesize stu; -(void) write{ NSLog(@"%d",sex); NSLog(@"%d",stu.age); NSLog(@"%s",stu.name); } @end

    測試程式碼如下

Person *person=[[Person alloc] init];
enum sex sex=female;
struct student stu={"cnblogs",12};
person.sex=sex;
person.stu=stu;
       
[person write];

    輸出結果如下

2014-03-26 22:13:10.112 ObjectEnum[524:303] 1
2014-03-26 22:13:10.115 ObjectEnum[524:303] 12
2014-03-26 22:13:10.116 ObjectEnum[524:303] cnblogs