【问题标题】:how to use enum when reading from a file从文件读取时如何使用枚举
【发布时间】:2015-12-21 20:44:02
【问题描述】:

我是 C++ 的初学者,我需要创建一些需要从文件中读取的与汽车相关的类。其中一个我想使用枚举 我的课是这样的:

enum engines{ gasoline, hybrid, diesel };

class Automobil
    {
    const int id;
    char *model;
    engines engine;
    int max_speed;
    int engine_cc;
    float avg_consumption_urban;
    float avg_consumption;
    float avg_speed_urban;
    float avg_speed;
}

我需要重载 >> 运算符以从文件中读取对象,但是当我为引擎执行此操作时,出现错误。我如何仍然保留枚举并从文件中读取?

friend ifstream& operator>>(ifstream& input, Automobil &a)
{
    delete[] a.model;
    input >> a.model;
    input >>a.engine; //error here
    input >> a.max_speed;
    input >> a.engine_cc;
    input >> a.avg_consumption_urban;
    input >> a.avg_speed_urban;
    input >> a.avg_consumption;
    input >> a.avg_speed;
    return input;

}

【问题讨论】:

  • 你为什么要删除a.model?
  • 我建议在互联网上搜索示例。我最近看到一个类似的问题。
  • 我从其他不必要的重载中复制了所有内容。我不太知道要搜索什么,因为我没有找到与我的问题相关的示例。
  • 我使用“stackoverflow c++ read enum”并遇到了这个问题:Reading in from a .txt file to a struct array that contains enum。看来我也回答了。 :-)
  • 顺便说一句,删除delete [] a.model;,因为您将读取已删除的内存,并且可以被其他函数重用。

标签: c++ file enums


【解决方案1】:

没有operator>> 的重载形式可以在枚举中读取。

你有两个选择:

  1. 读入枚举名称并转换为枚举类。
  2. 读入枚举值(数字)并转换为枚举类。

我更喜欢使用名称方法。将名称作为字符串读入,并在 [name, enum] 的表中查找以进行转换。

编辑 1:实现

std::map<std::string, enum engines> conversion_table;
// Initialization
conversion_table["gasoline"] = engines::gasoline;
conversion_table["hybrid"]   = engines::hybrid;
conversion_table["electric"] = engines::electric;

注意:您可能必须从值中删除 engines::

将文本转换为枚举:

engines engine_type = conversion_table[text];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    相关资源
    最近更新 更多