如何在C ++中向vector添加新对象

时间:2015-04-27 06:05:52

标签: c++ class object dynamic vector

我正在尝试创建一个程序,允许用户将名为Vehicle的类的对象添加到存储在vector中的库存中。 vector的初始大小为零。每个对象都是用户输入属性的工具。

我无法解决的问题是,如果每辆车都需要自己独立的物体,如何让用户继续添加车辆。如果用户决定继续向清单中添加更多车辆(对象)(vector称为carList),那么如何让C ++确定新对象的名称应该是什么。

有人可以引导我朝着正确的方向前进吗?如果这很明显,我很抱歉,我是该语言的新手。我必须做一些涉及动态分配对象或类似事物的事情吗?

这是我的(不完整)代码:

void addVehicle(vector<Vehicle> carList)
{
    char   stop;            // Needed for stopping the do-while loop 
    string VIN = "",        // Needed to hold user input for the VIN
           Make = "",       // Needed to hold user input for the Make
           Model = "";      // Needed to hold user input for the Model
    int    Year = 0;        // Needed to hold user input for the Year
    double Price = 0.0;     // Needed to hold user input for the Price

    cout << "You have chosen to add a vehicle to your inventory.\n\n";

    do
    {
        cout << "There are currently " << carList.size() << " vehicles in your inventory.\n\n"
             << "\t\t\tVehicle #" << (carList.size() + 1) << ": \n"
             << "\t\t___________________________\n\n";

        Vehicle /*new object needs to go here*/
        carList.push_back(/*new object from the line above*/);

        // Prompt user to input VIN
        cout << "VIN: ";
        cin >> VIN;

        // Prompt user to input Make
        cout << "Make: ";
        cin.ignore(); 
        getline(cin, Make);

        // Prompt user to input Model
        cout << "Model: ";
        getline(cin, Model);

        // Prompt user to input Year
        cout << "Year: ";
        cin >> Year;

        // Prompt user to input Price
        cout << "Price: $";
        cin >> Price;

        Call to the overloaded constructor to store user input in object
        /*(newly created object)*/.Vehicle::Vehicle(VIN, Make, Model, Year, Price);

        // Ask user if they would like to enter another vehicle
        cout << "\nWould you like to enter another vehicle? (Y/N):";
        cin.ignore();
        stop = cin.get();

    } while (stop != 'N');

}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:5)

您首先创建对象然后将副本推送到向量中?

Call to the overloaded constructor to store user input in object
Vehicle temp(VIN, Make, Model, Year, Price);
carList.push_back(temp);

但实际上不需要变量:

Call to the overloaded constructor to store user input in object
carList.push_back(Vehicle(VIN, Make, Model, Year, Price));

如果你有C ++ 11,你甚至可以直接构建对象:

Call to the overloaded constructor to store user input in object
carList.emplace_back(VIN, Make, Model, Year, Price);

看看马,没有副本!