2011-12-13 18 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、列挙型...? – 111111

+1

@ 111111 - 私はそれが彼が*私たちに求めているものだと思います。 –

答えて

5
enum Colors { Black, White }; 


int main() 
{ 
    Colors c = Black; 

    return 0; 
} 
+0

はい、それから、「 'Color': 'enum' type redefinition」と表示されます。 – 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; 
} 
関連する問題