我正在进行代码审查,看到将单引号字符串分配给枚举值:
enum { Option_1 = 'a', Option_2 = 'b' } ;
虽然这使得代码稍微更易读(尽管枚举的含义应该在名称中明确),但我觉得这看起来很傻。
我不知道你能否这样做,在研究后,我可以看出您使用的“字符”的二进制值只是被抛入int中。
其他人是否会实践这样做?还是这是一种不好的做法?
我正在进行代码审查,看到将单引号字符串分配给枚举值:
enum { Option_1 = 'a', Option_2 = 'b' } ;
虽然这使得代码稍微更易读(尽管枚举的含义应该在名称中明确),但我觉得这看起来很傻。
我不知道你能否这样做,在研究后,我可以看出您使用的“字符”的二进制值只是被抛入int中。
其他人是否会实践这样做?还是这是一种不好的做法?
根据ISO C和C++标准,这绝对是完全合法的。如果这些枚举值被序列化为文本(例如CSV)文件中的字符,则这是一种相当合理的做法。否则,我认为没有太多意义。我猜它可能会带来一些调试的好处,但我知道所有好的C/C++调试器都可以将枚举值解析为相应的符号。
这不是一个单引号字符串,而是一个字符字面量。在枚举中使用字符字面量实质上与将 char
赋值给 int
相同,完全合法,并且在许多情况下非常有用。
enum
{
Option_1 = 97,
Option_2 = 98
} ;
字符仅是1字节的整数,为什么不呢?
getc()
确实返回一个int
,因此尝试使用类似于 char c = getc(...);
的东西来存储结果是不合适的。 - GManNickG你甚至可以分配多字节的“值”,这些值最终可以达到32位整数:
enum t_f_fnf
{
true = 'true',
false = 'fals',
file_not_found = 'fnf!'
};
嗨,考虑一下我为您制作的这个简单示例, 正如您所看到的,使用枚举是合法的。在我的情况下,我将它们用作类的内部常量。享受吧。
#include <iostream>
using namespace std;
class VegetableBasket
{
enum { Max_Potatoes = 2 }; // This is a legal usage...
enum { Max_Tomatoes = 3 }; // In here the enums serve as class's internal constants
public :
// Constructors
VegetableBasket() : tomatoes(0), potatoes(0) {}
VegetableBasket(int t, int p) : tomatoes(t), potatoes(p)
{
if(tomatoes > Max_Tomatoes)
tomatoes = Max_Tomatoes;
if(potatoes > Max_Potatoes)
potatoes = Max_Potatoes;
}
// Accessors
int getMaxPotatoes() const { return Max_Potatoes; }
int getMaxTomatoes() const { return Max_Tomatoes; }
int getPotatoes() const { return potatoes; }
int getTomatoes() const { return tomatoes; }
private :
int tomatoes;
int potatoes;
};
void main()
{
VegetableBasket basket1(1, 1);
VegetableBasket basket2(5, 6);
cout << "The basket holds : " << basket1.getMaxPotatoes()
<< " max potatoes, and " << basket1.getMaxTomatoes()
<< " max tomatoes" << endl;
cout << "Basket 1 holds : " << basket1.getPotatoes()
<< " potatoes and " << basket1.getTomatoes()
<< " tomatoes" << endl;
cout << "Basket 2 holds : " << basket2.getPotatoes()
<< " potatoes and " << basket2.getTomatoes()
<< " tomatoes" << endl;
}
int
类型的,对吗? - GManNickG