【问题标题】:How to create objects of certain class by taking input from user如何通过获取用户的输入来创建特定类的对象
【发布时间】:2017-04-06 18:08:45
【问题描述】:

我有这个任务来写入和读取文件中的对象。但我无法得到的是如何通过用户输入创建某个类的对象。我仍在学习 CPP。这是我的代码 我有一个想法,但不知道它是否会起作用。创建像 Bus 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;
}

【问题讨论】:

  • 你不能只读写一个对象。应该先序列化它。

标签: c++ object


【解决方案1】:

这可以编译吗?看起来不像。

您期望“ch”在哪里获得值?

您不能在 case 语句中实例化 - 您至少需要将 case 语句的内容括在花括号之间。

成员函数调用应该类似于 'b1.Write();'。

最后,虽然写入二进制数据并将其读回应该可以工作,但它将是不可移植且易碎的。它可能无法在不同的编译器之间工作,而且几乎可以肯定不会在大端和小端系统之间工作。

【讨论】:

  • 感谢您的回答。它解决了我的问题。我在发布答案时跳过了开关盒的输入输出部分。
猜你喜欢
  • 2015-10-31
  • 2012-09-04
  • 1970-01-01
  • 2019-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多