使用c++模拟一个较为完整的超市购物系统
时间: 2024-01-08 21:01:53 浏览: 23
好的,以下是一个简单的超市购物系统的 C++ 实现:
```cpp
#include <iostream>
#include <vector>
#include <map>
#include <iomanip>
using namespace std;
// 商品类
class Product {
public:
string name; // 商品名称
double price; // 商品单价
Product(string n, double p) : name(n), price(p) {}
};
// 购物车类
class ShoppingCart {
public:
vector<Product> products; // 商品列表
void addProduct(Product p) {
products.push_back(p);
}
double totalPrice() {
double sum = 0;
for (Product p : products) {
sum += p.price;
}
return sum;
}
};
// 超市类
class SuperMarket {
public:
map<string, Product> products; // 商品列表
void addProduct(string name, double price) {
products[name] = Product(name, price);
}
void displayProducts() {
cout << "商品列表:" << endl;
cout << left << setw(20) << "名称" << setw(10) << "单价" << endl;
for (auto item : products) {
cout << left << setw(20) << item.second.name << setw(10) << item.second.price << endl;
}
}
ShoppingCart createShoppingCart() {
return ShoppingCart();
}
};
// 主函数
int main() {
SuperMarket market;
market.addProduct("苹果", 5.0);
market.addProduct("香蕉", 3.0);
market.addProduct("橙子", 4.0);
market.displayProducts();
ShoppingCart cart = market.createShoppingCart();
while (true) {
cout << "请输入要添加到购物车的商品名称(输入 q 结束):";
string name;
cin >> name;
if (name == "q") {
break;
}
if (market.products.count(name) == 0) {
cout << "找不到该商品,请重新输入!" << endl;
} else {
cart.addProduct(market.products[name]);
}
}
double totalPrice = cart.totalPrice();
cout << "您的购物车:" << endl;
cout << left << setw(20) << "名称" << setw(10) << "单价" << endl;
for (Product p : cart.products) {
cout << left << setw(20) << p.name << setw(10) << p.price << endl;
}
cout << "总价:" << totalPrice << endl;
return 0;
}
```
这个程序实现了一个简单的超市购物系统,包括商品类、购物车类、超市类。可以通过 `SuperMarket` 类添加商品,通过 `ShoppingCart` 类创建购物车,往购物车里添加商品,计算购物车的总价。