shangcheng/include/shopping_cart.hpp

71 lines
1.8 KiB
C++
Raw Normal View History

2026-05-06 02:54:13 +00:00
#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