【问题标题】:Make enums defined inside structs in C++ have global scope使 C++ 结构中定义的枚举具有全局范围
【发布时间】:2015-07-06 09:25:47
【问题描述】:

以下代码将编译为 C,但不会编译为 C++:

#include <stdio.h>

struct somestruct {
    int id;
    enum {
        STATE1 = 0,
        STATE2,
        STATE3,
        STATE4,
    } state;
};

int main(int argc, char *argv[])
{
    static struct somestruct s;

    if (s.state == STATE1) {
        printf("state1\n");
    }

    return 0;
}

在 C++ 中,我必须使用 somestruct::STATE1(因为枚举声明仅限于结构/类?)。 我正在进行的项目是用 C 编写的,但目前我们使用一些 C++ 库(Arduino),所以我们正在使用 C++ 编译器编译我们的 c 代码。那么有什么办法可以让上面的代码用C++编译呢?

【问题讨论】:

  • 重写它(将枚举拉出结构)?如果你不能重写它,你仍然可以用正确的 C++ 方式来使用它
  • 好问题(试过 extern "C",没用)
  • 是的,有办法。实际上,您必须已经知道它,因为您在问题中明确提到了它。使用somestruct::STATE1 而不是STATE1!!!

标签: c++ c enums scope compatibility


【解决方案1】:

您可以以兼容两种语言的形式对其进行编码,例如:

typedef enum 
{
    STATE1 = 0,
    STATE2,
    STATE3,
    STATE4,
} eState ;

struct somestruct 
{
    int id ;
    eState state ;
};

或者,如果您确实无法更改结构和枚举定义,则以下内容是可移植的(如果丑陋),并且要求您将每个 reference 更改为枚举而不是单个 definition(即 IMO 没有什么优点):

#if defined __cplusplus
    #define SOMESTRUCT(e) somestruct:: e
#else
    #define SOMESTRUCT(e) e
#endif

然后:

...
    if (s.state == SOMESTRUCT(STATE1)) {
...

【讨论】:

    【解决方案2】:

    使用using 语句将标识符带入调用范围:

    struct somestruct {
        int id;
        enum {
            STATE1 = 0,
            STATE2,
            STATE3,
            STATE4,
        } state;
    };
    
    #ifdef __cplusplus
    using somestruct::STATE1; // <-- here
    #endif
    

    【讨论】:

      【解决方案3】:

      在 C++ 中,是的,正如您所说:将其称为 somestruct::STATE1

      我不明白你将如何使这个在两种语言之间移植,但我又不明白你为什么需要这样做。在 C++ 代码中写 somestruct::STATE1,在 C 代码中写 STATE1。如果您真的需要在宏之间切换而不重复代码,请使用宏。

      别忘了修复你破碎的表情s-&gt;states 不是指针。

      【讨论】:

        【解决方案4】:

        您可以使用 c 宏定义

        #define STATE1 somestruct::STATE1
        

        应该允许进入状态 1 我建议不要这样做,因为您使用的是 c++ 编译器,因此您不妨利用它为您提供的 c++ 功能,然后放入 somestruct::STATE1。

        【讨论】:

          猜你喜欢
          • 2014-12-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多