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;
}
您不能只讀取和寫入對象。應該先序列化它。 –