c++ - C++ 中枚举的获取和设置

标签 c++ enums

我有一个名为 School 的类,其成员之一是枚举“SchoolType”,它有两个可能的值:Primary 和 secondary。以下是我的 School 头文件中的枚举:

 enum class SchoolType {
    Primary = 1,
    Secondary = 2
};

在我的主 C++ 文件中,我有一个函数 ReadSchool,它可以从用户输入中读取 School 的所有成员。所有其他成员都是 intstring 值,因此我在阅读这些值时没有遇到任何问题,但我不知道如何处理枚举。我最好的想法是这样做:

School ReadSchool()
{
    School tempSchool;
    int type;
    cout << "Name of School: ";
    tempSchool.SetName(GetString());
    cout << endl << "Type of School (1 = Primary, 2 = Secondary): ";
    cin >> type;
    if (type = 2)
        tempSchool.SetTypeSchool(2);        
    else
        tempSchool.SetTypeSchool(1);
    return tempSchool;
}

将 int 值放入我的 SetTypeSchool() 中不起作用,但写入 PrimarySecondary 也不起作用。我正在使用 Visual Studio 2015(如果这有什么区别的话)。任何人都可以提供一些清晰度或更好的方法来设置我的枚举值吗?感谢您的帮助

最佳答案

SchoolType GetSchoolType(string input)
{
    // DeHumanize our input
    if(input == "Primary")
    {
        return SchoolType::Primary;
    }
    else if(input == "Secondary")
    {
        return SchoolType::Secondary;
    }

    return SchoolType.None; // or throw an exception, or return a default SchoolType; up to you
}

关于c++ - C++ 中枚举的获取和设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34301828/

相关文章:

c# - EnumDataType() 属性验证错误消息未显示

scala - 如何将 Scala 枚举作为参数传递?

c++ - 将视频从RTP流保存​​到文件

c++ - opencv 的 reprojectImageTo3D() 中的深度图值

c++ - 如何在 Qt 中使用枚举?

c++ - 表达式未计算为 C++ VS 中的常量

c# - 缺少枚举的最后一项

Angular 6 全局枚举?

c++ - 哪种访问 C++ 枚举数的方式更好?

c++ - 快速的字符串搜索