c++ - C ++中的枚举与原始值?
问题描述
是否可以在 C++ 中为枚举提供原始值?
快速示例:
enum AnOperations: String {
case Addition = "+"
case Subtraction = "-"
case Division = "/"
}
// if or switch
if AnOperations.Addition.rawValue == "+" {
print("true")
}
解决方案
Swift
我必须承认,除了它的名字,我什么都不知道。
在 C++ 中,字符串不能用于枚举。
枚举声明:
枚举是一种独特的类型,其值被限制在一个值范围内(详见下文),其中可能包括几个显式命名的常量(“枚举数”)。常量的值是整数类型的值,称为枚举的基础类型。
(强调我的。)
什么可能有效:
enum AnOperations: char {
Addition = '+',
Subtraction = '-',
Division = '/'
};
因为char
是整数类型之一。
样本:
#include <iostream>
#include <sstream>
int main()
{
enum AnOperations: char {
Addition = '+',
Subtraction = '-',
Division = '/'
};
std::string text = "1 + 2";
std::istringstream in(text);
int arg1, arg2, result; char op;
in >> arg1 >> op >> arg2;
switch (op) {
case Addition: result = arg1 + arg2; break;
case Subtraction: result = arg1 - arg2; break;
case Division: result = arg1 / arg2; break;
default:
std::cerr << "Unknown op. '" << op << "'!\n";
return 1;
}
std::cout << arg1 << ' ' << op << ' ' << arg2 << " = " << result << '\n';
return 0;
}
输出:
1 + 2 = 3