作者ric2k1 (Ric)
看板EE_DSnP
標題[討論] int vs enum
時間Wed Dec 5 22:38:34 2007
雖然說 enum type 是表示 a set of constant integers,
enum 與 int 還是不能隨便轉換 ---
======
enum E { A, B };
int main()
{
E e;
e = 1;
int i = 2;
e = i;
int j = e;
}
======
cp44.cpp:6: error: invalid conversion from `int' to `E'
cp44.cpp:8: error: invalid conversion from `int' to `E'
所以說 conversion from enum to int 是可以的, e.g. int j = e;
但是 conversion from int to enum 就是 compiler error.
原因很簡單,
因為 enum 只是定義 subset of int.
conversing int to enum may produce illegal enum value.
而反之 (enum to int) 就不會有問題.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 59.121.132.121