(C++) "No operator " >> " matches these operands"枚举

(C++) "No operator ">>" matches these operands" with enumeration

本文关键字:gt these operands 枚举 matches C++ operator No      更新时间:2023-10-16

所以,我是一个完全的c++语言初学者,我正在做《Beginning c++ Through Game Programming》这本书中的一个练习,特别是第3章的第一个练习。它希望我使用std::coutswitch语句创建一个"困难选择程序",但是当我试图使用std::cin输入枚举类型difficulties的变量(myDifficulty)时,我发现了一个问题,在那里我在>>下得到上面的错误。下面是我的代码:

#include <iostream>
int main()
{
enum difficulties {EASY = 1, NORMAL, HARD, EXTREME};
difficulties myDifficulty;
std::cout << "EasynNormalnHardnExtremen";
std::cin >> myDifficulty;
switch (myDifficulty)
{
    case 1:
        std::cout << "You have chosen Easy as your difficulty." << std::endl;
        break;
    case 2:
        std::cout << "You have chosen Normal as your difficulty." << std::endl;
        break;
    case 3:
        std::cout << "You have chosen Hard as your difficulty" << std::endl;
        break;
    case 4:
        std::cout << "You have chosen Extreme as your difficulty. Good luck!" << std::endl;
        break;
}
system("pause");
return 0;
}

如果有人能帮忙,谢谢你。此外,如果我的代码有任何问题(它看起来如何等)反馈将非常感激!

p。这是我的第一个问题。:)

默认情况下,c++中没有定义enum类的operator>>,您需要创建自己的操作符:

std::istream& operator>> (std::istream& in, difficulties& diff) ;