C++中enum的使用
An enumeration is a distinct type whose value is restricted to a range of values,which may include several explicitly named constants ("enumerators"). The values of the constants are values of an integral type known as the underlying type of the enumeration. 如果1个变量只有几种可能的值,可以定义为枚举(enumeration)类型。所谓”枚举”是指将变量的值逐一罗列出来,变量的值只能在罗列出来的值的范围内。声明枚举类型用enum开头。 枚举类型(enumeration)是C++中的1种派生数据类型,它是由用户定义的若干枚举常量的集合: (1)、枚举中每一个成员(标识符)结束符是“,”,不是”;”,最后1个成员可省略”,”; (2)、初始化时可以赋负数,以后的标识符仍顺次加1; (3)、枚举变量只能取枚举说明结构中的某个标识符常量; (4)、在外部,可以对枚举变量进行赋值,但,需要进行类型转换; (5)、未辨别范围的枚举常数可以隐式转换为int,但是int不可以隐式转换为枚举值; (6)、将为枚举中的每一个名称分配1个整数值,该值与其在枚举中的顺序相对应,默许情况下,为第1个值分配0,为下1个值分配1,顺次类推,但可以显示设置枚举名称的值; (7)、为名称指定的值没必要是唯1的,即各枚举常量的值可以重复; (8)、在C语言中,枚举类型名包括关键字enum,在C++中允许不写enum,1般也不写enum,但保存了C的用法; (9)、枚举元素作为常量,它们是有值的,C++编译按定义时的顺序对它们赋值为0,1,2,3,…。也能够在声明枚举类型时另行指定枚举元素的值; (10)、枚举值可以用来作判断比较; (11)、1个整数不能直接赋给1个枚举变量; (12)、once enumerators are defined,their value can't be changed in program. 下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference: enum.hpp: #ifndef FBC_MESSY_TEST_ENUM_HPP_
#define FBC_MESSY_TEST_ENUM_HPP_
#include <iostream>
#include <string>
typedef short int16_t;
// reference: http://www.yolinux.com/TUTORIALS/C++Enum.html
class Day
{
public:
enum Enum
{
sunday = 0,monday,tuesday,wednesday,thursday,friday,saturday,InvalidDay
};
// Constructors
Day(void);
Day(Enum ee);
explicit Day(const std::string& ss);
// Overloaded assignment operators
Day& operator = (const Day& cc);
Day& operator = (const std::string& ss);
Day& operator = (Enum ee);
// Overloaded comparison operators
bool operator< (const Day& cc) const;
bool operator< (Enum ee) const;
bool operator<= (const Day& cc) const;
bool operator<= (Enum ee) const;
bool operator> (const Day& cc) const;
bool operator> (Enum ee) const;
bool operator>= (const Day& cc) const;
bool operator>= (Enum ee) const;
bool operator== (const Day& cc) const;
bool operator== (const std::string& ss) const;
bool operator== (const Enum ee) const;
bool operator!= (const Day& cc) const;
bool operator!= (const std::string& ss) const;
bool operator!= (const Enum ee) const;
// Accessor functions
inline std::string getString(void) const;
inline Enum getEnum(void) const;
inline int getValue(void) const;
private:
// Static functions
static Enum fromString(std::string ss);
static std::string toString(Enum ee);
static int toValue(Enum ee);
// Data members
Enum m_enum;
std::string m_string;
int m_value;
};
inline std::ostream& operator<< (std::ostream& _os,const Day& _e)
{
_os << _e.getString();
return _os;
}
inline std::string Day::getString(void) const
{
return m_string;
}
Day::Enum Day::getEnum(void) const
{
return m_enum;
}
int Day::getValue(void) const
{
return m_value;
}
int test_enum1();
int test_enum2();
int test_enum3();
int test_enum4();
int test_enum5();
int test_enum6();
#endif // FBC_MESSY_TEST_ENUM_HPP_
enum.cpp:#include "enum.hpp"
#include <iostream>
#include <string>
#include <algorithm>
/////////////////////////////////////////////////////////////
// reference: http://en.cppreference.com/w/cpp/language/enum
// enum that takes 16 bits
enum smallenum : int16_t {
a,b,c
};
// color may be red (value 0),yellow (value 1),green (value 20),or blue (value 21)
enum color {
red,yellow,green = 20,blue
};
// altitude may be altitude::high or altitude::low
enum class altitude : char {
high = 'h',low = 'l',// C++11 allows the extra comma
};
// the constant d is 0,the constant e is 1,the constant f is 3
enum {
d,e,f = e + 2
};
// enumeration types (both scoped and unscoped) can have overloaded operators
std::ostream& operator << (std::ostream& os,color c)
{
switch (c) {
case red: os << "red"; break;
case yellow: os << "yellow"; break;
case green: os << "green"; break;
case blue: os << "blue"; break;
default: os.setstate(std::ios_base::failbit);
}
return os;
}
std::ostream& operator << (std::ostream& os,altitude al)
{
return os << static_cast<char>(al);
}
int test_enum1()
{
color col = red;
altitude a;
a = altitude::low;
std::cout << "col = " << col << 'n' // col = red
<< "a = " << a << 'n' // a = 1
<< "f = " << f << 'n'; // f = 3
return 0;
}
/////////////////////////////////////////////////////////
// reference: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/
enum ItemType
{
ITEMTYPE_SWORD,ITEMTYPE_TORCH,ITEMTYPE_POTION
};
std::string getItemName(ItemType itemType)
{
if (itemType == ITEMTYPE_SWORD)
return std::string("Sword");
if (itemType == ITEMTYPE_TORCH)
return std::string("Torch");
if (itemType == ITEMTYPE_POTION)
return std::string("Potion");
}
int test_enum2()
{
// ItemType is the enumerated type we've declared above.
// itemType (lower case i) is the name of the variable we're defining (of type ItemType).
// ITEMTYPE_TORCH is the enumerated value we're initializing variable itemType with.
ItemType itemType(ITEMTYPE_TORCH);
std::cout << "You are carrying a " << getItemName(itemType) << "n"; // You are carrying a Torch
return 0;
}
////////////////////////////////////////////////////////////////////////////
// reference: http://www.yolinux.com/TUTORIALS/C++Enum.html
int test_enum3()
{
enum {
monday,sunday
} day;
day = wednesday;
if (day == saturday || day == sunday)
std::cout << "Day is a weekend day" << std::endl;
else if (day == wednesday)
std::cout << "Day is hump day - middle of the work week" << std::endl; // Day is hump day - middle of the work week
return 0;
}
//////////////////////////////////////////////////////////////////////////
int test_enum4()
{
typedef enum DAY_{
saturday = 0,sunday = 0,friday
} DAY;
DAY day_ = sunday;
if (day_ == 0)
std::cout << "Day is a weekend day" << std::endl; // Day is a weekend day
else if (day_ == wednesday)
std::cout << "Day is hump day - middle of the work week" << std::endl;
return 0;
}
//////////////////////////////////////////////////////////////////////////
// Constructors
Day::Day(void) : m_enum(sunday),m_string("Sunday"),m_value(0)
{}
Day::Day(Enum _e) : m_enum(_e),m_string(toString(_e)),m_value(0)
{}
Day::Day(const std::string& _s) : m_enum(fromString(_s)),m_string(_s),m_value(toValue(m_enum))
{}
// Assignment operators
Day& Day::operator= (const Day& _c)
{
m_string = _c.m_string;
m_enum = _c.m_enum;
m_value = _c.m_value;
return *this;
}
Day& Day::operator= (const std::string& _s)
{
m_string = _s;
m_enum = fromString(_s);
m_value = toValue(m_enum);
return *this;
}
Day& Day::operator= (Enum _e)
{
m_enum = _e;
m_string = toString(_e);
m_value = toValue(_e);
return *this;
}
bool Day::operator< (const Day& _c) const
{
return (m_value < _c.m_value);
}
bool Day::operator< (Enum _e) const
{
return (m_value < toValue(_e));
}
bool Day::operator<= (const Day& _c) const
{
return (m_value <= _c.m_value);
}
bool Day::operator<= (Enum _e) const
{
return (m_value <= toValue(_e));
}
bool Day::operator> (const Day& _c) const
{
return (m_value > _c.m_value);
}
bool Day::operator> (Enum _e) const
{
return (m_value > toValue(_e));
}
bool Day::operator>= (const Day& _c) const
{
return (m_value >= _c.m_value);
}
bool Day::operator>= (Enum _e) const
{
return (m_value >= toValue(_e));
}
bool Day::operator== (const Day& _c) const
{
return (m_enum == _c.m_enum);
}
bool Day::operator== (const std::string& _s) const
{
return (m_string == _s);
}
bool Day::operator== (const Enum _e) const
{
return (m_enum == _e);
}
bool Day::operator!= (const Day& _c) const
{
return (m_enum != _c.m_enum);
}
bool Day::operator!= (const std::string& _s) const
{
return (m_string != _s);
}
bool Day::operator!= (const Enum _e) const
{
return (m_enum != _e);
}
Day::Enum Day::fromString(std::string _s)
{
// Case insensitive - make all upper case
transform(_s.begin(),_s.end(),_s.begin(),toupper);
if (_s == "SUNDAY") return sunday;
else if (_s == "MONDAY") return monday;
else if (_s == "TUESDAY") return tuesday;
else if (_s == "WEDNESDAY") return wednesday;
else if (_s == "THURSDAY") return thursday;
else if (_s == "FRIDAY") return friday;
else if (_s == "SATURDAY") return saturday;
throw std::range_error("Not a valid Day value: " + _s);
return InvalidDay;
};
std::string Day::toString(Day::Enum _e)
{
switch (_e) {
case sunday: { return "SUNDAY"; }
case monday: { return "MONDAY"; }
case tuesday: { return "TUESDAY"; }
case wednesday: { return "WEDNESDAY"; }
case thursday: { return "THURSDAY"; }
case friday: { return "FRIDAY"; }
case saturday: { return "SATURDAY"; }
}
return "InvalidDay";
}
int Day::toValue(Day::Enum _e)
{
switch (_e) {
case sunday: { return 0; }
case monday: { return 2; }
case tuesday: { return 3; }
case wednesday: { return 4; }
case thursday: { return 5; }
case friday: { return 6; }
case saturday: { return 7; }
}
return 8; // Invalid
}
int test_enum5()
{
Day day;
day = "Saturday";
if (day == Day::saturday || day == Day::sunday)
std::cout << "Day is a weekend day" << std::endl; // Day is a weekend day
return 0;
}
/////////////////////////////////////////////////////////////
int test_enum6()
{
typedef enum {
monday,sunday
} Day;
const char *day_str[] = { "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday" };
Day day = saturday;
if (day == saturday || day == sunday)
std::cout << day_str[day] << std::endl; // Saturday
return 0;
}
GitHub:https://github.com/fengbingchun/Messy_Test (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |