正在加载……
专注、离线、切勿分心

typedef 声明新的类型名来代替已有的类型名。
声明INTEGER为整型:
typedef int INTEGER
声明结构类型:
     typedef struct{
         int month;
         int day;
         int year;}DATE;   // DATE 就代表结构体变量
声明 NUM 为整型数组类型 :
typedef int NUM[100];  ==> int == NUM

声明 STRING 为字符指针类型:
typedef char *STRING;  ==> char * == STRING

声明 POINTER 为指向函数的指针类型,该函数返回整型值 :
typedef int (*POINTER)();  ==> POINT 就是 int func_name () ; 类型的函数的地址
先按定义数组变量形式书写:int n[100];
将变量名n换成自己指定的类型名:
   int NUM[100];
在前面加上 typedef ,得到
   typedef int NUM[100];
用来定义变量:NUM n;//这里就直接用n去代替typedef 后面的NUM 

        void swap(int *a,int *b); 
     typedef void (*p)(int*,int*); 
     p z = swap; // swap函数的入口地址赋值给变量 z 
     z(a,b); 
(1) 用 typedef 可以声明各种类型名,但不能用来定义变量。
(2) 用 typedef 只是对已经存在的类型增加一个类型名,而没有创造新的类型。
(3) 当不同源文件中用到同一类型数据时,常用 typedef 声明一些数据类型,把它们单独放在一个文件中,然后在需要用到它们的文件中用 #include 命令把它们包含进来。
(4) 使用 typedef 有利于程序的通用与移植。
(5) typedef与#define有相似之处,例如:
typedef int COUNT     #define COUNT int  的作用都是用 COUNT 代表 int 。但事实上,它们二者是不同的。#define是在预编译时处理的,它只能作简单的字符串替换,而typedef是在编译时处理的。实际上它并不是作简单的字符串替换,而是采用如同定义变量的方法那样来声明一个类型。

#include<stdio.h>
#include<stdlib.h>
typedef void(*func1)();  //定义一个函数指针类型(比如我们说的int类型一个概念)
void func()
{
        printf("hello world\n");
}
int main()
{
        void (*pfunc)();  //定义一个函数指针
        //func1 = func;  //func1是一个类型,类似不能 int = a;
        func1 a = func;   //声明类型变量
        pfunc = func;     //函数指针赋值
        pfunc();
        a();
        system("pause");
}

           //注意在C和C++里不同
    在C中定义一个结构体类型要用typedef:
    typedef struct Student
    {
           int a;
    }Stu;
   Stu==struct Student    

              于是在声明变量的时候就可:Stu stu1;     (如果没有typedef就必须用  struct Student stu1;  来声明)
    另外这里也可以不写Student(于是也不能struct Student stu1;了,必须是Stu stu1;)
    typedef  struct
    {
           int a;
    }Stu;
    但在c++里很简单,直接
    struct  Student
    {
          int a;
    };    
    于是就定义了结构体类型Student,声明变量时直接Student stu2;
======================================================================================


    在c++中如果用typedef的话,又会造成区别:
    struct   Student  
    {  
           int   a;  
    }stu1;//stu1是一个变量  ,相当于Student stu1;

 
    typedef   struct   Student2  
    {  
          int   a;  
    }stu2; //stu2==struct Student2  

    使用时可以直接访问 stu1.a
    但是stu2则必须先   stu2 s2;         s2.a=10;        

======================================================================================


posted on 2017-04-23 20:50  正在加载……  阅读(183)  评论(0编辑  收藏  举报