[英]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.