【问题标题】:Is it possible to typedef union inside a struct in C是否可以在 C 中的结构内键入定义联合
【发布时间】:2022-01-05 05:38:39
【问题描述】:

我真的不明白联合是如何运作的。有人可以解释它是如何工作的吗?我可以 typedef 工会吗?如果答案是肯定的,我该怎么做?下面这段代码有什么问题?

typedef struct Car{
        int age;
        int weight;

        enum Type { Tesla, Lada } type;

        typedef union Consumption{
                double litre;
                int kwh;
        } Consumption;

        Consumption consumption;
} Car;

当我尝试编译此代码时出现错误代码:

union1.c:9:2: error: expected specifier-qualifier-list before ‘typedef’
  typedef union Consumption{
  ^~~~~~~

【问题讨论】:

  • 为什么要尝试?即使您可以定义它,C 也没有访问该联合所需的范围概念。它最终会在Car 之外。

标签: c struct union typedef


【解决方案1】:

typedef 不能存在于 structunion 内。然而,这并不意味着您不能在另一个内部定义 structunion。例如:

typedef struct Car{
        int age;
        int weight;

        enum Type { Tesla, Lada } type;

        union Consumption{
                double litre;
                int kwh;
        } consumption;
} Car;

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多