【发布时间】:2015-04-27 06:05:52
【问题描述】:
我正在尝试创建一个程序,该程序允许用户将名为 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');
}
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
如果不是
Vehicle类型的对象,而只是std::strings,你能解决这个问题吗?如果可以,您只需将其中一个替换为另一个即可在两者之间切换。
标签: c++ class object dynamic vector