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;
}
是彩色的類,結構,typedef,枚舉...? – 111111 2011-12-13 17:15:54
@ 111111 - 我認爲這就是他所要求的*我們*。 – 2011-12-13 17:18:17