【发布时间】:2020-05-25 07:29:35
【问题描述】:
我创建了一个应该将对象添加到向量并打印它们的程序,但是当我添加对象时它只打印添加的最后一个对象,我似乎找不到错误,这就是我所拥有的:
#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
【问题讨论】:
-
您是否尝试使用调试器逐行执行代码?没有按预期运行的线路是什么?
-
这里很可能没有理由使用
new。您可以将GroceryItem直接存储在向量中(而不是指向一个的指针)。 Why should C++ programmers minimize use of 'new'?
标签: c++ vector scope dynamic-memory-allocation