C++ 如何通过从用户获取输入来创建特定类的对象
我的任务是从文件中写入和读取对象。但我无法获得的是如何通过用户输入创建特定类的对象。我仍在学习CPP。这是我的密码 我有一个想法,但不知道它是否会工作。创建像总线b1(var1,var2,var3,var4)这样的对象。它会工作吗C++ 如何通过从用户获取输入来创建特定类的对象,c++,object,C++,Object,我的任务是从文件中写入和读取对象。但我无法获得的是如何通过用户输入创建特定类的对象。我仍在学习CPP。这是我的密码 我有一个想法,但不知道它是否会工作。创建像总线b1(var1,var2,var3,var4)这样的对象。它会工作吗 class Bus { private: int busno; string to; string from; float time; public: Bus()
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;
}
类总线
{
私人:
内特布斯诺;
串到;
串从;
浮动时间;
公众:
巴士()
{
busno=0;
至“”;
从“;
时间=0.0;
}
总线(int总线号、字符串到、字符串从、浮点时间)
{
此->总线号=总线号;
这个->到;
这个->从=从;
这->时间=时间;
}
无效写入()
{
流文件;
打开(“output.txt”);
file.fseekp(0,ios::end);
write((char*)this,sizeof(Bus));
file.close();
}
无效读取()
{
流文件;
打开(“output.txt”);
file.fseekg(0,ios::beg);
而(file.read((char*)this,sizeof(Bus));
{
这个能编译吗?看起来不像
您希望“ch”在哪里获得值
不能在case语句中实例化,至少需要将case语句内容括在花括号中
成员函数调用应类似于“b1.Write();”
最后,虽然写入二进制数据并将其读回应该可以工作,但它将是不可移植和脆弱的。它可能无法在不同的编译器之间工作,并且几乎肯定无法在大端和小端系统之间工作。您不能只读写对象。应该在之前序列化它。感谢您的回答。它解决了我的问题。我跳过了在发布答案时,ped开关盒的输入输出部分。