用枚举编写代码

writing code in enum

本文关键字:代码 枚举      更新时间:2023-10-16

我写了某种关于如何在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;

然后阅读枚举。