2017-09-07 99 views
0

下面是代碼:C++枚舉類正確

#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 

所以焦炭*印刷爲逗號,爲什麼呢?

+2

不,紅色會顯示'*',黃色顯示'',因爲ascii表是'* +, - ' – Petesh

+1

啊,我的壞。現在需要一杯咖啡。 – qed

回答

3

Red'*'Yellow'*' + 2,它是','

更具體地說,42是'*'的ASCII值,44爲',',和RedYellow由2

0

Ascii Code Table

區別你知道如何enum工作,enum GET值的變量+1最後一個值。爲前

enum { 
     sunday = 0, monday, tueday, ... , saturday 
} 

如果存取權限的monday它將1值。 ,因爲您已給出red = '*'。所以編譯器你的enum將看起來像這樣。

enum { 
     red = '*', 
     blue = '+', 
     yellow = ',' 
} 

所以現在你知道了。