【问题标题】:How to define a type with custom values? (typedef, enum)如何定义具有自定义值的类型? (类型定义,枚举)
【发布时间】:2011-12-13 17:10:14
【问题描述】:

在我的许多类的程序中,我使用Color 作为一个类型,它应该只有WHITEBLACK 作为它的可能值。

所以例如我想写:

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

和类似的东西。在我所有的类和标题中,我都说#include "ColorType.h",我有Color c 作为类属性,但我不知道在ColorType.h 中写什么。我尝试了typedef enum Color 的一些变体,但效果不佳。

【问题讨论】:

  • Color 是作为类、结构、类型定义、枚举...吗?
  • @111111 - 我想这就是他在问我们

标签: c++ types enums


【解决方案1】:
enum Colors { Black, White };


int main()
{
    Colors c = Black;

    return 0;
}

【讨论】:

  • @Vidak 那你就不知道怎么写头文件了。
【解决方案2】:

Let_Me_Be's answer 是简单/常用的方法,但 C++11 还为我们提供了class enums,如果这些是颜色的 only 选项,它可以防止错误。一个普通的枚举可以让你做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;
}

【讨论】:

    猜你喜欢
    • 2011-09-11
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2020-07-08
    相关资源
    最近更新 更多