2012-04-07 65 views
-1

這個問題讓我瘋狂。我需要把它做好,這樣我才能通過我的課程。謝謝你所有的嘗試。枚舉類型的操作在C++中是合法的嗎?

在C++中編寫一個簡單的程序來調查枚舉類型的安全性。在枚舉類型中至少包含10個不同的操作,以確定不正確或愚蠢的東西是合法的。

+1

你到目前爲止有什麼? – Lou 2012-04-07 03:05:03

+1

這是一個複雜的答案,我會很快發表一個答案,但是,展示你到目前爲止對我們和你而言是一個很大的幫助。 – josephthomas 2012-04-07 03:06:20

+2

哪個標準? C++ 03或C++ 11? – bitmask 2012-04-07 03:08:29

回答

-1

這是一個完全可操作的程序,顯示了十種不同類型的枚舉操作。細節將在代碼中,參考文獻將在帖子的底部。

首先,瞭解什麼是枚舉是非常重要的。有關此方面的參考資料,請參閱Enumerated Types - enums。在下面的代碼中,我使用數學運算,按位運算符並使用枚舉值將數組初始化爲默認大小。

#include <iostream> 
using namespace std; 

enum EnumBits 
{ 
    ONE = 1, 
    TWO = 2, 
    FOUR = 4, 
    EIGHT = 8 
}; 

enum Randoms 
{ 
    BIG_COUNT = 20, 
    INTCOUNT = 3 
}; 

int main(void) 
{ 
    // Basic Mathimatical operations 
    cout << (ONE + TWO) << endl; // Value will be 3. 
    cout << (FOUR - TWO) << endl; // Value will be 2. 
    cout << (TWO * EIGHT) << endl; // Value will be 16. 
    cout << (EIGHT/TWO) << endl; // Value will be 4. 

    // Some bitwise operations 
    cout << (ONE | TWO) << endl; // Value will be 3. 
    cout << (TWO & FOUR) << endl; // Value will be 0. 
    cout << (TWO^EIGHT) << endl; // Value will be 10. 
    cout << (EIGHT << 1) << endl; // Value will be 16. 
    cout << (EIGHT >> 1) << endl; // Value will be 4. 

    // Initialize an array based upon an enum value 
    int intArray[INTCOUNT]; 

    // Have a value initialized be initialized to a static value plus 
    // a value to be determined by an enum value. 
    int someVal = 5 + BIG_COUNT; 

    return 0; 
} 

上面完成的代碼示例可以用另一種方式來完成,這是你超載運營商|等爲EnumBits。這是一種常用技術,其他參考請參閱How to use enums as flags in C++?

有關位運算的參考,看看Bitwise Operators in C and C++: A Tutorial

使用C++ 11可以使用額外的方式,如strongly typed enums枚舉。

+0

**版主說明**此答案下的評論是純粹的噪音,並已清除。 – 2012-04-07 09:03:02