gpt4 book ai didi

c++ - C++ 中的枚举具有原始值?

转载 作者:行者123 更新时间:2023-12-02 17:35:32 25 4
gpt4 key购买 nike

是否可以为 C++ 中的枚举提供原始值?

Swift 示例:

enum AnOperations: String {
case Addition = "+"
case Subtraction = "-"
case Division = "/"
}

// if or switch
if AnOperations.Addition.rawValue == "+" {
print("true")
}

最佳答案

我必须承认,除了它的名字之外,我对 Swift 一无所知。

在 C++ 中,枚举中不能使用字符串。

<强> Enumeration Declaration :

An enumeration is a distinct type whose value is restricted to a range of values (see below for details), which may include several explicitly named constants ("enumerators"). The values of the constants are values of an integral type known as the underlying type of the enumeration.

(强调我的。)

什么可能有效:

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

Live Demo on coliru

关于c++ - C++ 中的枚举具有原始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58654881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com