以下声明之间的区别
Difference between the following declarations?
我有枚举类型,颜色:
enum colors {green, red, blue};
colors mycolors=red
是否与int yourcolors=red
相同,每个调查员的类型是否int
?两者的值均为 1,对吧?
谢谢!
我只想发布一些代码片段来证明 Jason Lang 和 Kerrek SB 的评论:
#include <iostream>
#include <typeinfo>
enum colors {green, red, blue};
int main()
{
colors mycolors=red;
int yourcolors=red;
if (mycolors == yourcolors)
std::cout << "same values" << std::endl;
if (typeid(mycolors) != typeid(yourcolors))
std::cout << "not the same types" << std::endl;
return 0;
}
运行此代码将导致以下控制台输出:
same values
not the same types
另外(正如丹尼尔·卡米尔·科扎尔(Daniel Kamil Kozar(所提到的(还有enum class
(只有C++11及以后!有关为什么更喜欢enum class
而不是enum
的更多信息,请参阅此问题。
关于"为什么enum
s之后不仅仅是int
s(或long
s或......(的问题,只需考虑运算符重载。这是++ colors(green) == 1
绝不能是真的。确认此问题,运算符重载对于普通enum
s和此问题以及可接受的答案,以查看如何避免在"枚举类"的重载运算符中进行转换。
最后请记住,enum
s的使用 - 如果使用合理 - 可以提高代码的可读性。
- 我认为
enum
似乎更安全一些。你可以做int yourcolors=red
,但不能colors mycolors=1
。 - 当我调试枚举时,使用枚举很有帮助。它显示枚举名称而不是它的价值。
- 枚举值不是左值。所以,当你经过他们时引用,不使用静态内存。这几乎和你一模一样将计算值作为文本传递。
enum KEYS
{
UP,
RIGHT,
DOWN,
LEFT
};
void (KEYS select)
{
switch (select)
{
case UP:
case RIGHT:
case DOWN:
case LEFT: break;
default: exit(1);
}
}
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 这 4 个 lambda 表达式之间有什么区别?
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- (double) 和 double() 之间的区别
- & 和 * 之间的区别
- std::is_convertible 和 std::convertible_to 之间的区别(在实践中)?
- 析构函数和'delete'之间的区别
- 在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- OpenMP #pragma omp for v/s #pragma omp parallel for 之间的区别?
- S() 与 S{} 之间的区别?