[英]Is it valid to use void* rather than any pointer type if we always static_cast<> it?
[英]Is there an alternative to input a enumerated type variable rather than using a static_cast
我試圖輸入一個枚舉類型變量,但如果不使用 static_cast 操作我就無法輸入
#include<iostream>
using namespace std;
enum month
{
JAN,
FEB,
MAY,
JUNE,
OCTOBER,
DECEMBER,
};
int main()
{
month This;
cin >> This; <<_______________________ Causes a compiler error
system("pause");
return 0;
}
一種解決方法是讀入一個整數,並使用 static_cast 強制編譯器將整數值放入枚舉類型
{
int input_month;
cin >> input_month;
month This = static_cast<month>(input_month);<<_____________Works
}
那么是否有輸入枚舉類型值的替代方法
這是一個示例,我將如何處理(擴展jacobi的答案)。
#include <iostream>
#include <stdexcept>
enum month
{
JAN,
FEB,
MAY,
JUNE,
OCTOBER,
DECEMBER,
};
month int2month(int m)
{
switch(m)
{
case 1: return month::JAN;
case 2: return month::FEB;
case 3: return month::MAY;
case 6: return month::JUNE;
case 10: return month::OCTOBER;
case 12: return month::DECEMBER;
default: throw std::invalid_argument("unknown month");
}
}
std::istream& operator>>(std::istream& is, month& m)
{
int tmp;
if (is >> tmp)
m = int2month(tmp);
return is;
}
int main()
{
month This;
try{
std::cin >> This;
}
catch(std::invalid_argument& e){
// TODO: handle
}
return 0;
}
注意,還有更多方法可以將“ int”映射到月份。 例如,我認為您的代碼將獲得與以下結果相同的結果:
month int2month(int m)
{
switch(m)
{
case 0: return month::JAN;
case 1: return month::FEB;
case 2: return month::MAY;
case 3: return month::JUNE;
case 4: return month::OCTOBER;
case 5: return month::DECEMBER;
default: throw std::invalid_argument("unknown month");
}
}
超出此問題的范圍:
另外請注意,您可以編寫一個“ string2month”函數。 然后,您可以將“ tmp”設置為字符串。 根據僅包含“ tmp”的數字,您可以將“ tmp”轉換為“ int”以將其轉換為一個月,或嘗試將“ tmp”轉換為“ month”。 這將允許像JAN或January這樣的輸入,具體取決於'string2month'的實現。
您必須為枚舉“月”實現自己的運算符>>才能執行所需的操作。
例:
std::istream& operator>>(std::istream& is, month& m)
{
int tmp;
if (is >> tmp)
m = static_cast<month>(tmp);
return is;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.