代码如下:
#include "stdafx.h"
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
enum Suit : long {Heart, Club, Spade, Diamond};
enum class Color : char {Red = '*', Blue, Yellow, Green};
int main(int argc, wchar_t* argv[])
{
using namespace std;
auto suit = Suit::Club;
auto color = Color::Yellow;
cout << setw(37) << left << "Suit value: " << setw(5) << right << suit << endl;
cout << setw(37) << left << "Suit value +10: " << setw(5) << right << suit + 10 << endl;
cout << setw(37) << left << "Color value: " << setw(5) << right << static_cast< char >(color) << endl;
cout << setw(37) << left << "Color value +10: " << setw(5) << right << static_cast< int >(color) << endl;
wchar_t x;
wcin >> x;
return 0;
}在vs2017中运行的结果:
Suit value: 1
Suit value +10: 11
Color value: ,
Color value +10: 44因此,字符*被打印为逗号,为什么?
发布于 2017-09-07 19:40:19

正如您知道enum是如何工作的,enum的变量从上一个值中获得值+1。对于前-
enum {
sunday = 0, monday, tueday, ... , saturday
}如果你访问monday的值,它将为1。就像你给red = '*'的一样。因此,对于编译器,您的enum将如下所示。
enum {
red = '*',
blue = '+',
yellow = ','
} 现在你知道了。
https://stackoverflow.com/questions/46091651
复制相似问题