避免使用与C ++中的枚举冲突的预定义数字常量

时间:2014-05-14 00:18:37

标签: c++ enums g++ naming-conventions

此问题与GCC says "syntax error before numeric constant" in generated header file from bisonI'm getting an error concerning enum (I think)有关,但其中的答案仅说明了为什么人们可能会看到错误,"错误:数字常量之前的语法错误。&# 34;除非我掩饰它,否则我没有看到任何好的解决方案来避免这个问题(当然除了简单地重命名我们的枚举常量)。因此,我的问题是:除了简单地重命名枚举常量以避免这种命名冲突,还有其他(更好的)方法来解决这个问题吗?使用命名空间似乎不起作用。

UPDATE(对于名称空间): 我收到这个错误:

enum.cpp:5:5: error: expected identifier before numeric constant
enum.cpp:5:5: error: expected ‘}’ before numeric constant
enum.cpp:5:5: error: expected unqualified-id before numeric constant
enum.cpp:7:1: error: expected declaration before ‘}’ token

来自这个计划:

#include <sys/ioctl.h>

namespace mine {
  enum test {
    NCC
  };
}

int main(int argc, char** argv)
{ 
  return 0;
}

注意,编译此程序时出现同样的错误:

#define NCC 5

namespace mine {
  enum test {
    NCC
  };
}

int main(int argc, char** argv)
{ 
  return 0;
}

2 个答案:

答案 0 :(得分:2)

我知道这样做的唯一方法是取消定义您要在枚举中重新定义的符号/符号:

#include <sys/ioctl.h>
#undef NCC

namespace {
    enum {
        NCC
    }
}

编译。

请记住,我假设您真的想要重新定义该符号。如果是这样,那你就是这样做的。

答案 1 :(得分:0)

在C ++中,您可以使用命名空间来保持它们不融合。