파일에서 객체를 쓰고 읽는 데이 과제가있었습니다. 그러나 사용자 입력에 의해 특정 클래스의 객체를 만드는 방법은 얻을 수 없습니다. 여전히 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;
}
개체를 읽고 쓸 수는 없습니다. 전에 serialize해야합니다. –