C++中enum的使用
來源:程序員人生 發布時間:2016-07-06 13:01:57 閱讀次數:2762次
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, tuesday, wednesday, thursday, friday, saturday, 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,
monday,
tuesday,
wednesday,
thursday,
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, tuesday, wednesday, thursday, friday, saturday, 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
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈