2017-04-06 58 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

感謝您的回答。它解決了我的問題。我在發佈答案時跳過了開關盒的輸入輸出部分。 –

相關問題