[英]Enumerations in C++ with raw values?
C++ 中的枚舉是否可以有原始值?
Swift 示例:
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;
}
Output:
1 + 2 = 3
您可以在 C++ 中使用 char 類型。
下面的作品
enum AnOperations : char {
ADDITION='+',
SUBSTRACTION='-',
DIVISION='/'
};
編譯時出現以下錯誤
enum AnOperationsSTR : std::string {
ADDITION = '+',
SUBSTRACTION = '-',
DIVISION = '/'
};
or
enum AnOperationsSTR : char[] {
ADDITION = '+',
SUBSTRACTION = '-',
DIVISION = '/'
};
所以,你可以像下面這樣使用。
int main(void)
{
printf("is %c == AnOperations:'+' : %s\n", '+', AnOperations::ADDITION == '+' ? "TRUE" : "FALSE");
printf("is %c == AnOperations:'+' : %s\n", '+', AnOperations::SUBSTRACTION == '+' ? "TRUE" : "FALSE");
return 0;
}
上面代碼的結果是,
is + == AnOperations:'+' : TRUE
is + == AnOperations:'+' : FALSE
正如其他人已經說過的那樣,您無法打開字符串,但您可以使用 map來實現相同的結果。 根據您的目的,這可能是矯枉過正。
void f( const char* s )
{
using function_t = std::function< void() >;
using string_to_function = map< string, function_t >;
static string_to_function m =
{
{"1234", f_1234}, // assosciate "1234" to function f_1234
{"ABCD", f_ABCD}, // assosciate "ABCD" to function f_ABCD
};
auto i = m.find( s );
return i == m.end()
? f_default() // not found in map
: i->second(); // found, so we call the function
}
而且,只是為了好玩,試試這個:
#include <iostream>
void f( int i )
{
switch ( i )
{
default: cout << "default"; break;
case 'ABCD': cout << "ABCD\n"; break;
case '1234': cout << "1234\n"; break;
}
}
int main()
{
f( '1234' );
f( 'ABCD' );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.