c++ - enum 类型不能接受 cin 命令

标签 c++ enums

请看这段代码:

#include <iostream>
using namespace std;
int main()
{

    enum object {s,k,g};
    object o,t;

    cout << "Player One: "; cin >> o;
    cout << "Player Two: "; cin >> t;

    if (o==s && t==g) cout << "The Winner is Player One.\n";
    else if (o==k && t==s) cout << "The Winner is Player One.\n";
    else if (o==g && t==k) cout << "The Winner is Player One.\n";
    else if (o==g && t==s) cout << "The Winner is Player Two.\n";
    else if (o==s && t==k) cout << "The Winner is Player Two.\n";
    else if (o==k && t==g) cout << "The Winner is Player Two.\n";
    else cout << "No One is the Winner.\n";
        return 0;
}

在编译时我会得到这个错误:no match for 'operator>>' in 'std::cin >> o 我正在使用代码块。那么这段代码有什么问题呢?

最佳答案

枚举没有运算符>>()。您可以自己实现一个:

std::istream& operator>>( std::istream& is, object& i )
{
    int tmp ;
    if ( is >> tmp )
        i = static_cast<object>( tmp ) ;
    return is ;
}

当然,如果你只是 cin 一个整数并自己转换会更容易。只想向您展示如何编写 cin >> 运算符。

关于c++ - enum 类型不能接受 cin 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10371681/

相关文章:

c++ - 使用函数重载在 C++ 中调用具有整数的 char 等效函数

正在跳过 c++ for 循环

C++ 不能将变量声明为抽象类型

java - 为具有 n 个状态的 FSM 定义状态。 (java)

objective-c - 枚举自定义 : Is it possible to create subEnum?

c++ - OpenGL 3D 旋转看起来不像预期的那样

c++ - 设计建议 : calling a method on the container object from the contained object

c# - 有没有一种简单的方法可以在Flags中写入以2为底的数字?

string - 在 Rust 中匹配 Option 静态字符串文字

java - 当无法泛化时,正确转换为作为参数传递的未知类型