【问题标题】:How to input an object in C++?如何在 C++ 中输入对象?
【发布时间】:2021-12-31 14:09:29
【问题描述】:

您好,下面的代码是一个简单的 C++ 类示例

#include <iostream>
using namespace std;

class Car {        // The class
  public:          // Access specifier
    string brand;  // Attribute
    string model;  // Attribute
    int year;      // Attribute
    Car(string x, string y, int z) {  // Constructor with parameters
      brand = x;
      model = y;
      year = z;
    }
};

int main() {
  // Create Car objects and call the constructor with different values
  Car carObj1("BMW", "X5", 1999);
  Car carObj2("Ford", "Mustang", 1969);

  // Print values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}
// W3Schools

在我看来,定义对象的方法是用如下代码编写它:&lt;ClassName&gt; &lt;ObjectName&gt;

现在我的问题是:有没有办法输入一个对象?喜欢cin &gt;&gt; ObjectName;

在我们输入对象名称后,我们输入参数。

有可能吗?

【问题讨论】:

标签: c++ class object input


【解决方案1】:

您不能从命令行输入对象名称,但是,您可以创建一个默认构造的对象,然后通过重载 operator&gt;&gt; 从输入中填充其属性。

class Car {
  public:
    Car() = default;
    // ...
};

std::istream& operator>>(std::istream& in, Car& car) {
  in >> car.brand >> car.model >> car.year;
  return in;
}

int main() {
  Car carObj1;
  cout << "Enter a car brand, model, and year: ";
  cin >> carObj1;
  // ...
}

【讨论】:

    【解决方案2】:

    是的,C++ 中有运算符重载,您可以重载 > 运算符。这是一个示例代码:

    #include <iostream>
    using namespace std;
    
    class Car {        // The class
      public:          // Access specifier
        string brand;  // Attribute
        string model;  // Attribute
        int year;      // Attribute
        Car(string x, string y, int z) {  // Constructor with parameters
          brand = x;
          model = y;
          year = z;
        }
    
        Car() = default;
    
        void Carinput(std::istream& is)
        {
            is >> brand >> model >> year;
        }
    
        void carOutput(std::ostream& os) const
        {
            os << brand << " " << model << " " << year << std::endl;
        }
    };
    
    std::istream &operator>>(std::istream &is,Car &car)
    {
        car.Carinput(is);
        return is;
    }
    
    std::ostream &operator<<(std::ostream &os,const Car &car)
    {
        car.carOutput(os);
        return os;
    }
    
    int main() {
      // Create Car objects and call the constructor with different values
      Car carObj1("BMW", "X5", 1999);
      Car carObj2("Ford", "Mustang", 1969);
    
      // Print values
      cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
      cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
    
      std::cout << "\n*============================================*\n"
                << std::endl;
    
      std::cout << "Your input:" << std::endl;
      Car carObj3;
      std::cin >> carObj3;
      std::cout << carObj3;
    
      return 0;
    }
    
    

    【讨论】:

      【解决方案3】:

      这是其中一种方法:

      #include<iostream>
      #include<vector>
      
      
      class Car
      {
      public:
          Car( const std::string& brand, const std::string& model, int year )
          : m_brand( brand ), m_model( model ), m_year( year ) // initialize members like this
          {
          }
      
          std::string m_brand;
          std::string m_model;
          int m_year;
      };
      
      int main ()
      {
          std::vector< Car > cars; // use an std::vector to store the objects
          std::string brand( "" );
          std::string model( "" );
          std::string year( "" );
          
      
          std::cout << "How many cars do you want to add? ";
          std::string count( "" );
          std::getline( std::cin, count ); // get input as string using std::getline()
          int carCount { std::stoi( count ) }; // converts it to type int before 
                                               // assigning it to carCount
      
          cars.reserve( carCount ); // reserve some space in vector to avoid 
                                    // unnecessary allocations and slowdowns
      
          for ( int idx = 0; idx < carCount; ++idx )
          {
              std::cout << "Enter the brand name of car number " << idx + 1 << ": ";
              std::getline( std::cin, brand );
      
              std::cout << "Enter the model name of car number " << idx + 1 << ": ";
              std::getline( std::cin, model );
      
              std::cout << "Enter the production year of car number " << idx + 1 << ": ";
              std::getline( std::cin, year );
      
              cars.emplace_back( Car( brand, model, std::stoi( year ) ) ); // push the new Car
          }                                                                // instance to the
                                                                           // vector called cars
          std::cout << '\n';
      
          for ( int idx = 0; idx < carCount; ++idx )
          {
              std::cout << "Info for car number " << idx + 1 << ": "
              << cars[ idx ].m_brand << " " << cars[ idx ].m_model << " " << cars[ idx ].m_year << "\n";
          }
          return 0;
      }
      

      这是输出:

      How many cars do you want to add? 2
      Enter the brand name of car number 1: Porsche
      Enter the model name of car number 1: GT3 RS
      Enter the production year of car number 1: 2019
      Enter the brand name of car number 2: BMW
      Enter the model name of car number 2: M6
      Enter the production year of car number 2: 2016
      
      Info for car number 1: Porsche GT3 RS 2019
      Info for car number 2: BMW M6 2016
      

      但是请记住,这个类仍然需要做很多工作,比如添加成员函数(如 getter 和 setter)等。所以这不是我编写类的方式。我只是想保持简单,以便您可以轻松理解这些概念。

      【讨论】:

        猜你喜欢
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 2020-10-22
        • 2013-12-18
        • 2018-01-15
        • 1970-01-01
        • 2011-01-23
        • 1970-01-01
        相关资源
        最近更新 更多