2017-04-06 27 views
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; 
} 
+0

您不能只读取和写入对象。应该先序列化它。 –

回答

0

这是编译吗?它看起来不像。

你在哪里期待'ch'获得价值?

您不能在case语句中实例化 - 至少需要在大括号之间包含case语句内容。

成员函数调用应该看起来像'b1.Write();'。

最后,在编写二进制数据并读回它应该工作,它将是不可移植和脆弱的。它可能不适用于不同的编译器之间,几乎可以肯定在大小系统之间不起作用。

+0

感谢您的回答。它解决了我的问题。我在发布答案时跳过了开关盒的输入输出部分。 –

相关问题