zoukankan      html  css  js  c++  java
  • 联合体

    1.联合:计算机为其中最大的字段分配空间。

    例如:

    typedef union
    {
      short count;
      float weight;
      float volume;
    }quantity;     //占4字节

    2.设置联合的值

    C89方式(保存第一个字段的值):quantity q = {4};  注意加上{}

    指定初始化器(按名设置联合字段的值):quantity q = {.weight=1.5}; 也能设置结构字段的初值

    点表示法:  quantity q;

           q.volume = 3.7;

    3.结构体常和联合体一起使用

     例如:

    typedef union
    {
        float lemon;
        int lime_pieces;
    }lemon_lime;
    
    typedef struct
    {
        float tequila;
        float cointreau;
        lemon_lime citrus;
    }margarita;
    
    margarita m = {2.0,1.0,{0.5}};
    margarita b = {2.0,1.0,{.line_pieces=1}};

    4.枚举

    enum colors {red,green,puce};

    enum colors favorite = puce;

    5.结构和联合用分号分割数据项,而枚举用逗号

    练习(枚举)

    #include <stdio.h>
    
    typedef enum
    {
        COUNT,POUNDS,PINTS
    }unit_of_measure;
    
    typedef union
    {
        short count;
        float weight;
        float volume;
    }quantity;
    
    typedef struct
    {
        const char *name;
        const char *country;
        quantity amount;
        unit_of_measure units;
    }fruit_order;
    
    void display(fruit_order order)
    {
        printf("This order contains");
        if(order.units == PINTS)
            printf("%2.2f pints of %s
    ",order.amount.volume,order.name);
        else if (order.units == POUNDS)
            printf("%2.2f lbs of %s
    ",order.amount.weight,order.name);
        else
            printf("%i %s
    ",order.amount.count,order.name);
    }
    
    int main()
    {
        fruit_order apples = {"apples","England",.amount.count=144,COUNT};
        fruit_order strawberries = {"strawberries","Spain",.amount.weight=17.6,POUNDS};
        fruit_order oj = {"orange juice","U.S.A",.amount.volume=10.5,PINTS};
        display(apples);
        display(strawberries);
        display(oj);
        return 0;
    }
  • 相关阅读:
    traceroute命令
    Apache部署django项目
    Linux中变量#,#,@,0,0,1,2,2,*,$$,$?的含义
    Python正则表达式
    Python 字符串格式化 (%操作符)
    Python初学者的一些编程技巧
    Linux命令 ls -l 输出内容含义详解
    Django 前后台的数据传递示列
    hibernate基础(一)
    MySQL之多表
  • 原文地址:https://www.cnblogs.com/syyy/p/5700917.html
Copyright © 2011-2022 走看看