zoukankan      html  css  js  c++  java
  • 结构体

    1.定义的基本结构

    struct Name {
       //一些基本的数据结构或者自定义的数据类型 
    };

    2.可以使用的形式

    struct studentInfo {
       ..... 
    }Alice,Bob,stu[1000];

    注:结构体里面能定义除了自身(这样会引起循环定义的问题)之外的任何数据类型。不过虽然不能定义本身,但可以定义自身类型的指针变量。

    struct node {
       struct node n;  //不能定义node型变量
       struct node *next;  //可以定义node*型指针变量  
    };

    3.访问结构体内元素

    例形式如下的结构体

    struct studentInfo{
        int id;
        char name[20];
        studentInfo *next;
    }stu,*p;

    则访问的形式如下:

    访问stu变量的写法:
        stu.id    stu.name    stu.next
    访问指针变量p中元素的写法:
        (*p).id    (*p).name    (*p).next
    结构体指针变量内元素的访问只需要使用“->”跟上要访问的元素即可,两者等价
        p->id    p->name    p->next

    4.结构体的初始化

    4.1 单个赋值

      如:stu.id=1

    4.2 struct 结构体名 变量名={初始数据表};

    4.3 “构造函数”的方法

      直接定义在函数体内,不需要写返回类型,且函数名与结构体名相同

    4.3.1 默认构造函数,形式如下

    struct studentInfo{
       int id;
       char gender;
       studentInfo(){}   //默认生成的构造函数   
    };

    4.3.2手动初始化参数

    struct studentInfo{
       int id;
       char gender;
        //下面的参数用以对结构体内部变量进行赋值
       studentInfo(int _id,int _gender){
           id=_id;
           gender=_gender; 
        } 
    };
    //或简化的形式
    struct studentInfo{
       int id;
       char gender;
       studentInfo(int _id,int _gender):id(_id),gender(_gender) {}
    };

     赋值方法:studentInfo stu=studentInfo(10086,'M');

    5.结构体数组

      所谓结构体数组,是指数组中的每个元素都是一个结构体,举例如下:

    struct translation {
        int code;
        char *desc;
    };
    
    struct translation t1[] = { 
        {1, "translation1"},
        {2, "translation2"},
        {3, "translation3"},
        {0, NULL}    //手动添加结束标志,防止超出
    };
    
    struct translation t2[] = { 
        {9, "translation9"},
        {8, "translation8"},
        {7, "translation7"},
        {0, NULL}    //同上
    };

    在main文件中调用时的方法

     1 extern struct translation t1[];
     2 extern struct translation t2[];
     3 
     4 //遍历translation类型所有结构体数组的方法
     5 struct translation *translations[] = { 
     6     t1,
     7     t2,
     8     NULL
     9 };
    10 
    11 //调用举例
    12 static char *search_desc(int errcode)
    13 {
    14     int i = 0;
    15     struct translation *error;
    16     while (NULL != translations[i]) {
    17         error = &(translations[i++][0]);
    18         while (NULL != error->desc) {
    19             if (errcode == error->errorcode)
    20                 goto __exit;
    21             error++;
    22         }
    23     }   
    24 __exit:
    25     return error->desc;
    26 }
  • 相关阅读:
    SQLyog远程连接Linux服务器错误2003解决
    Linux/UNIX系统编程手册 练习3.8
    概括
    Linux 命令
    句柄类
    带有C风格的 CLib库
    Linux 命令
    C++ 编程思想 第三章 3-2
    一.创建型模式 Prototype 模式
    一.创建型模式 Builder
  • 原文地址:https://www.cnblogs.com/nanzh/p/8027901.html
Copyright © 2011-2022 走看看