[英]Specific features and use of enums in C++ [on hold]
除了枚舉允許定義常量之間的關系並提高代碼可讀性這一事實之外,我想在這里討論這種類型的不同用途。
Indeed, unlike Java for example, C++ enum type is more permissive and behaves like a customizable integer type: its underlying type can be fixed, it does not require specified values, it allows different values than those specified, it is implicitly convertible to int
.
優缺點都有什么?
你知道使用的例子嗎?
我還發布了我遇到的實際案例的答案。
謝謝你。
1. 為自定義 output 格式定義一個 integer 類型
雖然我首先沒有找到任何目的,但后來我注意到可以重寫 I/O 運算符來為這種類型格式化 output,如下例所示。
#include <iostream>
enum hexa : unsigned int {};
static std::ostream& operator<<(std::ostream &out, const hexa &n) noexcept {
const std::ios_base::fmtflags &flags = out.flags();
out << std::hex << std::showbase << std::uppercase << (unsigned int)n;
out.flags(flags);
return out;
}
int main(){
int a = 0x42F05;
hexa b = (hexa)0x42F05;
std::cout << a << std::endl;
std::cout << b << std::endl;
}
Output:
274181
0X42F05
2.定義一個范圍integer類型
從文檔:
如果源值 [...] 適合最小的位字段,其大小足以容納目標枚舉的所有枚舉數,則它在范圍內。 請注意,此類轉換后的值可能不一定等於為枚舉定義的任何命名枚舉數。
因此,可以定義一個類整數類型,它只接受指定范圍內的值,如下所示:
#include <iostream>
enum range { min=0, max=31 };
int main(){
range a = (range)5;
range b = (range)32;
std::cout << a << std::endl;
std::cout << b << std::endl;
}
Output:
test.cpp: In function 'int main()':
test.cpp:8:19: warning: the result of the conversion is unspecified because '32' is outside the range of type 'range' [-Wconversion]
range b = (range)32;
^~
5
32
3.打印人類可讀的值和I18N
這是我最近使用的一個實際案例。 我有一個返回 integer 的方法,它代表星期幾,並通過我的代碼使用,但我想將它打印為人類可讀的值和不同的語言。 感謝枚舉,我解決了我的問題。
#include <iostream>
enum dayofweek { monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=7 };
static std::ostream& operator<<(std::ostream &out, const dayofweek &wday) noexcept {
switch(wday){
case monday : return out << "Monday";
case tuesday : return out << "Tuesday";
case wednesday : return out << "Wednesday";
case thursday : return out << "Thursday";
case friday : return out << "Friday";
case saturday : return out << "Saturday";
case sunday : return out << "Sunday";
default : return out << "(N/A)";}
}
/* static int today(){ return 5; } */
static dayofweek today(){ return (dayofweek)5; }
int main(){
int a = today(); //backward compatibility
dayofweek b = today();
std::cout << a << std::endl;
std::cout << b << std::endl;
}
Output:
5
Friday
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.