shangcheng/include/shopping_cart.hpp

71 lines
1.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ifndef MALL_SHOPPING_CART_HPP
#define MALL_SHOPPING_CART_HPP
#include "product.hpp"
#include <vector>
#include <utility>
/**
* @brief 购物车条目,记录商品和购买数量。
*/
struct CartItem {
Product product; ///< 商品副本
int quantity = 0; ///< 购买数量
/** @brief 小计金额 = 单价 × 数量 */
double subtotal() const noexcept { return product.getPrice() * quantity; }
};
/**
* @brief 购物车类,管理用户选中的商品。
*/
class ShoppingCart {
public:
ShoppingCart() = default;
/**
* @brief 向购物车添加商品(若已存在则累加数量)。
* @param product 商品
* @param quantity 数量
*/
void addItem(const Product& product, int quantity);
/**
* @brief 从购物车移除指定商品(完全移除)。
* @param productId 商品编号
* @return true 移除成功false 未找到
*/
bool removeItem(uint64_t productId);
/**
* @brief 修改某商品的数量。
* @param productId 商品编号
* @param quantity 新数量≤0 则移除)
* @return true 修改成功
*/
bool updateQuantity(uint64_t productId, int quantity);
/** @brief 清空购物车 */
void clear();
/** @brief 获取所有条目 */
const std::vector<CartItem>& getItems() const noexcept { return items_; }
/**
* @brief 计算购物车总金额。
* @return 所有条目小计之和
*/
double totalPrice() const;
/** @brief 购物车是否为空 */
bool isEmpty() const noexcept { return items_.empty(); }
/** @brief 条目数量 */
size_t itemCount() const noexcept { return items_.size(); }
private:
std::vector<CartItem> items_; ///< 购物车条目列表
};
#endif // MALL_SHOPPING_CART_HPP