【发布时间】: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;,因为您将读取已删除的内存,并且可以被其他函数重用。