【发布时间】:2019-06-12 09:33:24
【问题描述】:
我有一个表示单个产品对象的产品类,每个新产品对象都存储在一个向量中,该向量是目录类的一部分。我希望用户能够将存在于目录向量中的产品添加到他的购物车中,这是另一个有一个向量来保存他想要订购的产品的类。我希望通过从 Catalog 向量复制到购物车向量来完成此操作。
产品类别
class Product
{
private:
// int id;
// Category category;
std::string name;
std::string description;
float price;
unsigned short int stock;
public:
Product(std::string name, std::string description, float price,
unsigned short int stock);
void setId(int id);
// void setCategory(Category category);
void setName(std::string name);
void setDescription(std::string description);
void setPrice(float price);
void setStock(unsigned short int stock);
int getId();
// Category getCategory();
std::string getName();
std::string getDescription();
float getPrice();
};
目录类
class Catalog
{
// friend class ShoppingCart;
private:
std::vector<Product> catalog;
std::vector<Product>::iterator it;
public:
/**
* TODO: The createProduct(), deleteProduct() and updateProduct() method should only be accessible by the admin user
*/
std::vector<Product> getCatalog();
// add product to catalog -> admin
void productCreate(Product p);
// delete product from catalog -> admin
void productDelete(std::string name);
// update a product -> admin
void productUpdate(std::string &name);
// list products inside catalog
void productList();
// search products
bool productSearch(std::string name);
};
ShoppingCart 类
class ShoppingCart
{
private:
// vector that contains products to order
std::vector<Product> shoppingCart;
Catalog catalog;
// int quantity;
public:
void cartList();
int cartSize();
void addToCart(std::string);
void deleteFromCart(std::string);
void clearCart();
};
由于这个项目是基于文本的(终端),我希望用户能够通过输入产品名称将产品添加到他的购物车中。我的逻辑可以在下面的代码中看到:
来自 ShoppingCart 类的 addToCart 方法
void ShoppingCart::addToCart(string name)
{
/**
* BUG: Doesnt add objects to the shoppingcart vector
*/
for (Product p : catalog.getCatalog())
{
if (p.getName() == name) {
shoppingCart.push_back(p);
} else {
printf("Oops.. %s doesn't seem to exist in our catalog.",
name.c_str());
}
}
}
接收用户输入的视图
void View::shoppingcart()
{
string productName;
cout << "Add to cart: ";
cin >> productName;
cart.addToCart(productName);
printf("You added '%s'", productName.c_str());
cout << endl;
}
当我执行此代码时,没有给出任何错误,但实际上没有任何内容被添加到购物车向量中,大小保持为 0。做错了什么?或者我在这里错过了什么?请记住,我是 C++ 编程的新手。
【问题讨论】:
-
您是否看到“糟糕……我们的目录中似乎不存在 %s。”留言?
-
我的 ESP 告诉我,您在添加任何
Products 之前将您的Catalog对象复制到您的ShoppingCart对象,但您发布的代码还不够肯定地说。 minimal reproducible example 可以提供帮助。 -
@Raffallo 抱歉,我想在帖子中提到这一点,但不,它永远不会涉及到那部分。所以没有错误或任何表明我做错了什么的迹象。
-
class ShoppingCart中有成员Catalog catalog。这真的是您商店中所有可用产品的目录吗?如果没有,您尝试从可能始终为空的本地成员复制。恐怕你的概念有问题…… -
假设,您同意
Catalog catalog的生命周期比任何ShoppingCart实例的生命周期长,您可以执行以下操作:将class ShoppingCart中的Catalog catalog更改为Catalog &catalog,即一个参考。您必须在class ShoppingCart的构造函数中使用“全局”目录对其进行初始化。因此,每个购物车都可以使用它的引用成员来访问全局目录。
标签: c++ algorithm vector data-structures