簡體   English   中英

如何用自定義值定義類型? (typedef,枚舉)

[英]How to define a type with custom values? (typedef, enum)

在我的程序中的許多類中,我都使用Color作為類型,並且它應該僅具有WHITEBLACK作為其可能的值。

因此,例如,我想寫:

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

和類似的東西。 在我所有的類和標題中,我都說#include "ColorType.h" ,並且我將Color c作為類屬性,但是我不知道在那個ColorType.h寫什么。 我嘗試了一些typedef enum Color變體,但效果typedef enum Color

enum Colors { Black, White };


int main()
{
    Colors c = Black;

    return 0;
}

Let_Me_Be的答案是簡單/常用的方法,但是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM