enum 类型不能接受 cin 命令

新手上路,请多包涵

请看这段代码:

 #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 我正在使用代码块。那么这段代码有什么问题呢?

原文由 Inside Man 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 462
1 个回答

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

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

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

原文由 Matchman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题