• 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
  • 相关阅读:
    CSS颜色代码大全
    swfuploadphp上传说明
    projectlocker 使用
    十大简单易用的免费在线HTML编辑器
    c#读取docx(ooxml)
    直接在网页上显示word2007文档
    树莓派4b noMachine远程连接4000端口问题
    visual studio问题集合
    设置TrackMouseEvent捕获WM_MOUSEHOVER和WM_MOUSELEAVE消息
    atlwin中不停发WM_PAINT消息原因分析
  • 原文地址:https://www.cnblogs.com/jiuyi/p/10094681.html
Copyright © 2020-2023  润新知