简体   繁体   English

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

[英]Avoiding predefined numeric constants conflicting with enumerations in C++

This question is related to GCC says "syntax error before numeric constant" in generated header file from bison and I'm getting an error concerning enum (I think) , but the answers there only gave the reason for why one might see the error, "error: syntax error before numeric constant." 这个问题与GCC有关,它是由bison在生成的头文件中说“数值常量前的语法错误”, 我遇到了一个关于enum的错误(我认为) ,但是那里的答案仅给出了为什么有人会看到该错误的原因, “错误:数字常量之前的语法错误。” Unless I glossed over it, I didn't see any good solutions to avoid this problem (except of course to simply rename our enumeration constants). 除非我不加掩饰,否则我看不出任何避免这种问题的好方法(当然只是简单地重命名我们的枚举常量)。 Thus, my question is: besides simply renaming enum constants to avoid this naming conflict, are there other (preferable) ways to get around this problem? 因此,我的问题是:除了简单地重命名枚举常量以避免这种命名冲突外,还有其他(首选)方法可以解决此问题吗? Using namespaces does not seem to work. 使用名称空间似乎不起作用。

UPDATE (for namespaces): I get this error: 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

from this program: 从这个程序:

#include <sys/ioctl.h>

namespace mine {
  enum test {
    NCC
  };
}

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

Note, I get the same error when compiling this program: 注意,编译该程序时会出现相同的错误:

#define NCC 5

namespace mine {
  enum test {
    NCC
  };
}

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

The only way I know of to do this is to undefine the contants/symbols you're about to redefine in your enumeration: 我唯一知道的方法是取消定义要在枚举中重新定义的内容/符号:

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

namespace {
    enum {
        NCC
    }
}

This compiles. 这样编译。

Keep in mind that I'm assuming you really want to redefine that symbol. 请记住,我假设您确实要重新定义该符号。 If so, that's how you do it. 如果是这样,那就是您的做法。

在C ++中,可以使用名称空间使它们保持混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM