C++ Enumration 列舉
以enum為宣告字眼,給予列舉名稱,後面大括號寫入列舉元
enum 列舉名{列舉元1, 2, 3....};
給予列舉元指定常數,不選擇用常數而用列舉元來表示狀態,讓程式更加清楚
#include <iostream>
using namespace std;
int main(){
// 沒有特別指定數字給列舉元會從0往上遞加
enum status {sit, stand, walk, run};
status checkStatus = sit;
cout << "status number: " << checkStatus << endl; // 0
checkStatus = stand;
cout << "status number: " << checkStatus << endl; // 1
checkStatus = walk;
cout << "status number: " << checkStatus << endl; // 2
checkStatus = run;
cout << "status number: " << checkStatus << endl; // 3
// 有指定數字給列舉元,且指定數字可以重複
enum menu {pork = 1, beef, noodles = 4, rice};
menu order = pork;
cout << "order number: " << order << endl; // 1
order = beef;
cout << "order number: " << order << endl; // 2
order = noodles;
cout << "order number: " << order << endl; // 4
order = rice;
cout << "order number: " << order << endl; // 5
// 不能直接指定數字給列舉元
// order = 5; error
// 可以拿列舉元來做運算
cout << order + 8 << endl; // 13
order = rice;
// 以下兩個if statement 是正確可行的
if (order == 5) {
cout << "you have ordered the rice." << endl;
}
if (order == rice) {
cout << "you have ordered the rice." << endl;
}
// 不能使用postfix increment or decrement
// cout << order++ << endl;
// 不能使用prefix increment or decrement
// cout << ++order << endl;
int i = 1;
cout << menu(i) << endl;
// 代替常數來作為判別狀態 or 作為傳入函式的參數
}
應用
代替常數作為傳入函式的參數
代替常數來代表狀態,更容易給撰寫者表明用意
#include <iostream>
using namespace std;
enum status {sit, stand, walk, run};
void getStatus(status);
int main(){
int i = 4;
getStatus(status(i));
status s = sit;
getStatus(s);
}
void getStatus(status s) {
cout << "s : " << s << endl;
switch(s){
case 0:
cout << "You are sitting now, you can choose stand as next step."<< endl;
break;
case 1:
cout << "You are standing now, you can choose either sit or walk." << s << endl;
break;
case 2:
cout << "You are walking now, you can choose either stand still or run. " << s << endl;
break;
case 3:
cout << "You are running now, you can choose to walk." << s << endl;
break;
default:
cout << "You are not in the right status" << endl;
}
}
沒有留言:
張貼留言