简体   繁体   中英

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." 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:

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 ++中,可以使用名称空间使它们保持混乱。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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