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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM