2011-12-13 67 views
-1

在我的許多課程中,我使用Color作爲類型,它應該只有WHITEBLACK作爲它的可能值。如何用自定義值定義類型? (typedef,enum)

因此,例如,我想寫:

Color c; 
    c = BLACK; 
    if(c == WHITE) std::cout<<"blah"; 

和類似的東西。在我的所有課程和標題中,我說過#include "ColorType.h",而我有Color c作爲課程屬性,但我不知道該寫什麼ColorType.h。我嘗試了一些typedef enum Color的變體,但它沒有完全解決。

+1

是彩色的類,結構,typedef,枚舉...? – 111111 2011-12-13 17:15:54

+1

@ 111111 - 我認爲這就是他所要求的*我們*。 – 2011-12-13 17:18:17

回答

5
enum Colors { Black, White }; 


int main() 
{ 
    Colors c = Black; 

    return 0; 
} 
3

Let_Me_Be's answer是最簡單的/常規的方式,但C++ 11也給我們class enums這防止錯誤,如果這些是顏色的只有選項。定期枚舉讓你做Colors c = Colors(Black+2);,這沒有任何意義

enum class Colors { Black, White }; 

你可以(有點)通過之類的東西複製與C++ 03此功能:(IDEOne demo

class Colors { 
protected: 
    int c; 
    Colors(int r) : c(r) {} 
    void operator&(); //undefined 
public: 
    Colors(const Colors& r) : c(r.c) {} 
    Colors& operator=(const Colors& r) {c=r.c; return *this;} 
    bool operator==(const Colors& r) const {return c==r.c;} 
    bool operator!=(const Colors& r) const {return c!=r.c;} 
    /* uncomment if it makes sense for your enum. 
    bool operator<(const Colors& r) const {return c<r.c;} 
    bool operator<=(const Colors& r) const {return c<=r.c;} 
    bool operator>(const Colors& r) const {return c>r.c;} 
    bool operator>=(const Colors& r) const {return c>=r.c;} 
    */ 
    operator int() const {return c;} //so you can still switch on it 

    static Colors Black; 
    static Colors White; 
}; 
Colors Colors::Black(0); 
Colors Colors::White(1); 

int main() { 
    Colors mycolor = Colors::Black; 
    mycolor = Colors::White; 
}