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;
    }
  • 相关阅读:
    升级CentOS内核
    npm、component、spm、bower的区别
    Bower的使用
    Mac安装Bower
    Bower是什么?
    Mac下安装与配置Go语言开发环境
    jenkins升级为2.134
    nexus实现从windows迁移至Linux平台
    Jenkins构建完成后实现自动将war包部署到指定服务器
    使用jenkins构建一个maven项目
  • 原文地址:https://www.cnblogs.com/syyy/p/5700917.html
Copyright © 2011-2022 走看看