zoukankan      html  css  js  c++  java
  • Object C学习笔记21-typedef用法

     在上一章的学习过程中遇到了一个关键字typedef,这个关键字是C语言中的关键字,因为Object C是C的扩展同样也是支持typedef的。

      

      一. 基本作用

        typedef是C中的关键字,它的主要作用是给一个数据类型定义一个新的名称,这些类型报告内部数据类型,比如int,char 还有自定义类型struct,enum等。

        typedef一般有两个作用:(1) 给某种类型顶一个定义比较容易记的名字,相当于别名;(2)简化较为复杂的类型声明。

      二. typedef的使用

        1. 定义新类型

        语法:typedef 类型 新类型

    #import <Foundation/Foundation.h>
    typedef int newint;
    typedef newint firstint;
    int main(int argc, const char * argv[])
    {
        @autoreleasepool {
            newint a=5;
            NSLog(@"%d",a);
            firstint b=19;
            NSLog(@"%d",b);
        }
        return 0;
    }

        typedef int newint 将类型int重新定义为newint类型,在后面的代码中我们可以看出使用 newint a=5; 这里出现了新的类型newint,而这个等价于

      int a=5。 继续看 typedef newint firstint 这里使用的newint定义一个新类型firstint。 在后面的代码中声明变量firstint b=19 同样通过,这个等价于

      newint b=19 等价于 int b=19 ,从上面可以看出他们之间是可以传递的。

      2. 函数指针

        在使用到函数指针的时候,因为很多C方面的语法有欠缺,很多都是重新去查找资料温习,可能在某些地方还有错误。

        语法: typedef 返回值类型 (*新类型) (参数列表)

    int newfunc(int num){
        return num+100;
    }
    
    int main(int argc, const char * argv[])
    {
        @autoreleasepool {
            
            typedef int (*myfun)(int);
            myfun fun=newfunc;
            int value=(*fun)(100);
            NSLog(@"%d",value);
        }
        return 0;
    }

        上面的代码中定义了一个新的函数newfunc 其中返回值类型为int,有一个输入参数也是int。

        在main方法中使用typedef 给函数newfunc定义了一个新的指针类型myfun。 然后这个类型指向了newfunc函数。

        3. typedef 结构体和枚举

        关于结构体和枚举可以参考文章:    Object C学习笔记19-枚举   Object C学习笔记20-结构体

        对比下面两段代码,看看使用typedef的struct和不使用typedef的struct的不同之处

        不使用typedef的struct

    struct Student{
          int age;
    };
    struct Student stu ;
    stu.age=34;
    NSLog(@"%d",stu.age);

      首先定义了一个Student 的struct 类型,如果要定义一个Student 的变量,必须使用struct Student stu,stu2 格式;

            typedef struct Student{
                int age;
            } stu;
        
            stu a,b;
            a.age=45;
            b.age=32;
            NSLog(@"%d",a.age);

        上面代码的作用就相当于给结构类型struct Student 指定了一个新名称 stu,所以在后面的使用的时候就不需要使用struct Student 可以直接使用stu即可。而使用enum 类型也是同样如此。

      三. 复杂声明

        先看看这个是什么东西 int (*(*func[7][8][9])(int*))[5];  能看懂不,看不懂,理解需要点水平,到目前为止我也只是半懂的状态,这里不能班门弄斧的讲解复杂的声明。这里可以建议看一篇文章 "C 复杂声明"

  • 相关阅读:
    docker镜像构建之docker commit(七)
    docker常用容器命令(五)
    docker常用镜像命令(四)
    如何查看systemctl启动服务的日志
    window server 2012 无法安装.NET framework 3.5 service pack 1
    SpringBoot第六篇-SpringBoot+Mybatis+SpringSecurity+JWT整合,开发工具IDea
    SpringBoot第五篇SpringSecurity 认证机制
    SpringBoot第四篇常见问题
    SpringBoot第三篇SpringBoo和Mybatis整合
    SpringBoot第二章拦截器
  • 原文地址:https://www.cnblogs.com/jiuyi/p/10094709.html
Copyright © 2011-2022 走看看