2011-12-13 3 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

로 등 색상 : 정기적 열거 당신은 (다소) 등의 작업을 통해 C++ 03이 기능을 복제 할 수 있습니다

enum class Colors { Black, White }; 

감각을하지 않는, 당신이 Colors c = Colors(Black+2);을 수행 할 수 있습니다 클래스, 구조체, typedef, enum ...? – 111111

+1

@ 111111 - 그게 그가 우리에게 물어 보는 것 같아요. * –

답변

5
enum Colors { Black, White }; 


int main() 
{ 
    Colors c = Black; 

    return 0; 
} 
+0

네, 그렇지만 "Color": 'enum'타입 재정의를 말합니다. – Vidak

+0

@Vidak 그러면 헤더 파일을 쓰는 방법을 알 수 없습니다. –

+0

예 예, 죄송합니다, 잊어 버렸습니다 #ifndef :) 감사합니다! – Vidak

3

Let_Me_Be's answer은 보통/쉬운 방법이지만, 그 색상에 대한 옵션 인 경우 C++ (11)은 또한 우리에게 실수를 방지 class enums을 제공합니다. (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; 
} 
관련 문제