std::cin 提取到枚举
我不明白为什么我不能这样做:
enum MyEnum {X=1, Y};
...
X x;
std::cin >> x;
问题是 C++ 不够聪明,或者我弄错了什么?
I don't understand why I can't to that:
enum MyEnum {X=1, Y};
...
X x;
std::cin >> x;
the problem is that C++ is not smart enougth or I'm mistaking something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以,但您需要编写自定义
operator>>
重载:无法使用默认
std::istream
operator>> 执行此操作的原因是
重载的特点是右侧参数必须与运算符重载的参数完全匹配,因为它是由非常量引用获取的(因为运算符将通过分配给对象来修改对象)。另一种选择是将流中的整数表示形式提取到
int
中,然后将其转换为枚举类型:您可能希望在此处执行一些错误检查,除非您确定提取的值是可以用
MyEnum
表示。 (从技术上讲,您还应该小心提取到int
,因为int
可能无法表示MyEnum
的所有值。有一个在另一个问题的答案中解释如何做到这一点,如何扩展词法转换以支持枚举类型?)You can, but you need to write a custom
operator>>
overload:The reason you cannot do this with the default
std::istream
operator>>
overloads is that the right side argument must exactly match the parameter of the operator overload because it is taken by non-const reference (because the operator is going to modify the object by assigning to it).Another option would be to extract the integer representation from the stream into an
int
and then cast it to the enumeration type:You probably want to perform some error checking here, unless you are certain that the extracted value is able to be represented by
MyEnum
. (Technically, you should also be careful with extracting toint
, sinceint
may not be able to represent all the values ofMyEnum
. There's an explanation of how to do this in an answer to another question, How can I extend a lexical cast to support enumerated types?)