简体   繁体   中英

C++ enum [string] error

I am using an enum to declare types of variables. However, I get an error on each string saying: Error: expression must be an integral constant expression . And if I change the "" to '' , the words which are five characters or over give the error: Error: too many characters in a character constant . What should I do?

typedef enum
{
    INT = "int",
    STRING = "string",
    BOOLEAN = "bool",
    CHARACTER = "char",
    DOUBLE = "double",
    FLOAT = "float",
    LONG = "long",
    SHORT = "short"
} variable_types;

I don't think enums can be mapped to characters / strings. You can use an std::map<> to map the values to string values.

How to easily map c++ enums to strings

The enum type wasn't made for representing strings. IF you read a bit about it, you'll notice it stores only int types inside. If you need to map values like that, enum isn't really a good choice.

If you want to keep your syntax, use the #define command:

#define INT "int"
#define STRING "string"
...
#define SHORT "short"

You can also combine your current code with a std::map :

#include <map>
typedef enum
{
    INT,
    STRING,
    ...
    SHORT
} enumeratedTypes;
map<enumeratedTypes,string> variable_types;
variable_types[INT] = "int";
variable_types[STRING] = "string";
...
variable_types[SHORT] = "short";

Or just check things via an switch statement, if you need it for a function:

string foo(enumeratedTypes type){
   int choice = type;
   switch(choice){
   case INT:
      return "int";
   case STRING:
      return "string";
   ...
   case SHORT:
      return "short";
   default:
      return "error";
 }

Enums must be integral values. If you want, you can then use the enum values as indices into an array of strings.

Like so:

#include <vector>
#include <string>

enum variable_types
{
    INT,
    STRING,
    BOOLEAN,
    CHARACTER,
    DOUBLE,
    FLOAT,
    LONG,
    SHORT
};

// ...

const std::vector<std::string> enumNames = { "int", "string", "bool", ... };
variable_types someEnum = ...;
auto enumName = enumNames[someEnum];

As far as I know C/CPP standard does not support string-value enumerations. The value of the enumerations must be an integer (signed-unsigned and length depends on compiler)

If you put your string in '' marks that means that the string shall be interpreted as a character and - of course - a character has an integer value (0-255). Since in the marks there are more than one character the compiler will complain.

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