我创建了一个程序,该程序应该将对象添加到矢量中并打印它们,但是当我添加对象时,它仅打印最后添加的对象,我似乎找不到这就是我所拥有的错误:
#include <vector>
#include <iostream>
#include <string>
int main() {
std::vector<GroceryItem*> item;
GroceryItem* grocery = new GroceryItem;
std::string option = " ";
while((option != "x") && (option != "X")){
std::cout << "Welcome to Kroger\n";
std::cout << "A- add item\n";
std::cout << "X - Exit\n";
std::cout << "type option:";
std::cin >> option;
std::cin.ignore();
if(option == "A" || option == "a") {
std::cout << "Enter UPC, Product Brand, Product Name, and Price\n";
std::string item_;
double price_ = 0.0;
std::getline(std::cin, item_);
grocery->upcCode(item_);
std::getline(std::cin, item_);
grocery->brandName(item_);
std::cin.ignore();
std::getline(std::cin, item_);
grocery->productName(item_);
std::cin >> price_;
grocery->price(price_);
item.push_back(grocery);
} else if(option == "x" || option == "X") {
std::cout << "Here is an itemized list of the items in your shopping basket:\n";
for (GroceryItem* gcry : item) {
std::cout << *gcry;
}
}
}
}
这是在.cpp上声明的重载提取运算符
std::ostream& operator<<( std::ostream& stream, const GroceryItem& groceryItem ) {
stream << "\"" << groceryItem.upcCode() << "\", " << "\"" << groceryItem.brandName() << ", "
<< groceryItem.productName() << ", " << groceryItem.price() << "\n";
return stream;
这是示例输出:
Welcome to Kroger
A- add item
X - Exit
type option:a
Enter UPC, Product Brand, Product Name, and Price
2134567890
heinz
ketchup
222
Welcome to Kroger
A- add item
X - Exit
type option:a
Enter UPC, Product Brand, Product Name, and Price
2345678
coca cola
coke
3.33
Welcome to Kroger
A- add item
X - Exit
type option:x
Here is an itemized list of the items in your shopping basket:
"2345678", "coca cola, oke, 3.33
"2345678", "coca cola, oke, 3.33
您的grocery
变量是一个指针,这意味着它指向一个对象,当您更改指针的变量时,指针和向量中的对象都将被更改。
[就像弗拉德建议的那样,尝试将其移动到循环中,如果您正在使用delete
,请不要忘记使用new
移动此语句
GroceryItem* grocery = new GroceryItem;
在循环内。
例如
std::string option = " ";
while((option != "x") && (option != "X")){
std::cout << "Welcome to Kroger\n";
std::cout << "A- add item\n";
std::cout << "X - Exit\n";
std::cout << "type option:";
std::cin >> option;
std::cin.ignore();
if(option == "A" || option == "a") {
GroceryItem* grocery = new GroceryItem;
//...
而且在此代码片段中似乎忽略了调用
std::getline(std::cin, item_);
grocery->brandName(item_);
std::cin.ignore(); // <===
std::getline(std::cin, item_);
应删除。