gpt4 book ai didi

c++ - 使 C++ 中结构内部定义的枚举具有全局范围

转载 作者:太空狗 更新时间:2023-10-29 21:41:01 24 4
gpt4 key购买 nike

以下代码将编译为 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++编译呢?

最佳答案

您可以将其编码为与两种语言兼容的形式,例如:

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

struct somestruct
{
int id ;
eState state ;
};

或者,如果您真的不能更改结构和枚举定义,那么以下是可移植的(如果丑陋的话),并且需要您将每个引用更改为枚举而不是单个定义(即它在 IMO 上没有什么优点):

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

然后:

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

关于c++ - 使 C++ 中结构内部定义的枚举具有全局范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29903988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com