【发布时间】: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