我有一个名为 School 的类,其成员之一是枚举“SchoolType”,它有两个可能的值:Primary 和 secondary。以下是我的 School 头文件中的枚举:
enum class SchoolType {
Primary = 1,
Secondary = 2
};
在我的主 C++ 文件中,我有一个函数 ReadSchool
,它可以从用户输入中读取 School 的所有成员。所有其他成员都是 int
和 string
值,因此我在阅读这些值时没有遇到任何问题,但我不知道如何处理枚举。我最好的想法是这样做:
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()
中不起作用,但写入 Primary
或 Secondary
也不起作用。我正在使用 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/