c ++枚举可转换为int?

时间:2015-07-05 13:57:42

标签: c++ enums

根据http://www.cplusplus.com/doc/tutorial/other_data_types/

  

使用enum声明的枚举类型的值可以隐式转换为整数类型int,反之亦然。事实上,这种枚举的元素总是在内部分配一个整数数字等价,它们成为别名。如果没有另外指定,则等于第一个可能值的整数值为0,等于第二个的整数值为1,第三个等于2,依此类推......

所以,按照这个想法,我想看看以下样本是否有效:

#include <iostream>
using namespace std;

enum colors {white, yellow, red, green, blue, black};

int main()
{
  colors a{3};
  colors b{1};
  colors c{a-b};
  cout << c << '\n' << (c == red) << '\n' << c+20 << '\n';
  return 0;
}

它按预期工作,但只有在我设置-fpermissive标志时,否则g++会吐出编译错误。即使设置了这个标志,我仍然会收到一些警告,例如:invalid conversion from ‘int’ to ‘colors’

如果我正确理解文档,上述示例应该100%符合标准。但是,显然根据g++而不是{注意单词&#34; 无效&#34;)。

我甚至想要进一步推动这种可兑换性并尝试这样的事情:colors d{yellow}; d++;(希望d成为red)。但是,这次我不能让这个工作。我明白了:

enum.cpp:13:22: warning: no ‘operator++(int)’ declared for postfix ‘++’, trying prefix operator instead [-fpermissive]
   colors d{yellow}; d++;
                      ^
enum.cpp:13:22: error: no match for ‘operator++’ (operand type is ‘colors’)

我的示例中的代码是否正确?如果是这样,是否可以如上所述增加enum变量?

提前致谢。

0 个答案:

没有答案