0
我有这个任务从文件写入和读取对象。但我无法得到的是如何通过用户输入创建某个类的对象。我仍在学习CPP。这是我的代码 我有一个想法,但不知道它是否会工作。创建对象像总线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;
}
您不能只读取和写入对象。应该先序列化它。 –