【发布时间】:2017-04-06 18:08:45
【问题描述】:
我有这个任务来写入和读取文件中的对象。但我无法得到的是如何通过用户输入创建某个类的对象。我仍在学习 CPP。这是我的代码 我有一个想法,但不知道它是否会起作用。创建像 Bus b1(var1,var2,var3,var4) 这样的对象。它会起作用吗?
class Bus
{
private:
int busno;
string to;
string from;
float time;
public:
Bus()
{
busno=0;
to="";
from"";
time=0.0;
}
Bus(int busno,string to,string from,float time)
{
this->busno=busno;
this->to-to;
this->from=from;
this->time=time;
}
void Write()
{
fstream file;
file.open("output.txt");
file.fseekp(0,ios::end);
file.write((char*)this,sizeof(Bus));
file.close();
}
void Read()
{
fstream file;
file.open("output.txt");
file.fseekg(0,ios::beg);
while(file.read((char*)this,sizeof(Bus)));
{
cout<<"The bus no is "<<busno;
cout<<"The bus will run from "<<from;
cout<<"The bus will run till "<<to;
cout<<"The bus will run at time "<<time;
}
file.close();
}
};
int main()
{
int ch;
int busno;
string to,from;
float time;
while(1)
{
switch(ch)
{
case 1:
Bus b1(1234,x,y,19.30);
Bus.Write();
break;
case 2:
Bus.Read();
break;
}
}
return 0;
}
【问题讨论】:
-
你不能只读写一个对象。应该先序列化它。