用枚举编写代码
writing code in enum
我写了某种关于如何在class
中访问我的字段的方法,但我的老师告诉我应该使用enum
。
如何重写此代码以使用 enum
而不使用 goto
s?
void SetType() {
cout << "Book SetType" << endl;
Choice: cout << "Please Select from the list: n "
<< "1- Technical literature n "
<< "2- Fiction literature n "
<< "3- Textbook" << endl;
int i;
cin >> i;
switch (i) {
case 1:
Type = "Technical literature";
break;
case 2:
Type = "Fiction literature";
break;
case 3:
Type = "Textbook";
break;
default:
cout << "Erorr you entered a wrong choice" << endl;
goto Choice;
}
}
只是使用循环而不是gotos,它将是一个意大利面条代码。枚举可以不关心定义的数字,因为如果您添加新的数字,它们会自动递增。
#include <iostream>
#include <string>
void SetType();
using namespace std;
string Type;
int main()
{
SetType();
cout << "so you choose " << Type << endl;
return 0;
}
enum select
{
Technical_literature = 1,
Fiction_literature,
Textbook
};
void SetType() {
cout<<"Book SetType"<<endl;
while(1)
{
cout<<"Please Select from the list: n 1- Technical literature n 2- Fiction literature n 3- Textbook"<<endl;
int i;
cin >> i;
switch(i) {
case Technical_literature:
Type="Technical literature";
return;
case Fiction_literature:
Type="Fiction literature";
return;
case Textbook:
Type="Textbook";
return;
default:
cout << "Erorr you entered a wrong choice" << endl;
}
}
}
你的老师的意思是,与其到处硬编码常量,不如将你的 i 声明为枚举。
enum some_type {
type_techlit=1, type_fiction, type_textbook
};
some_type i;
然后阅读枚举。
相关文章:
- 如何公开库的枚举,以便我的代码不必键入整个命名空间来使用该枚举?
- 在C++代码中使用的 C 标头中向前声明枚举
- 如何编写一个错误结构,该结构可以包含不同的强键枚举作为错误代码
- 为每个枚举器添加代码
- 无法使用在模板化基类 [C++] 中声明的枚举编译代码
- 如何将C++代码中的枚举转换为 C
- 是否有一种有效的,适当的方法将非常大的公共班级枚举放在利用它们的公共方法之下,以使代码更加干净
- 如何将通用错误代码枚举与 system_category 中的错误代码一起使用<system_error>?
- 用枚举编写代码
- 枚举已安装产品的升级代码
- 将错误代码枚举与 std::error_code 进行比较
- 枚举不适用于代码等模板
- 在类定义中声明类型(枚举、结构等)会增加代码大小
- 理解这段代码:C++、#define 表和枚举
- 返回枚举,看不懂代码行
- 如何识别int代码值属于枚举中的哪个常量
- 永远不会达到打开枚举后的保护代码
- 为什么要使用这段代码来获取枚举成员的数量?
- 在Objective c++代码中转换objc整数和c++枚举
- 我如何消除这个枚举到字符串映射代码的样板文件?