用c++写一个商品订购系统
时间: 2023-12-30 07:02:59 浏览: 140
好的,以下是一个简单的C++商品订购系统的代码示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 商品类
class Product {
public:
Product(string name, int price) {
this->name = name;
this->price = price;
}
string getName() {
return name;
}
int getPrice() {
return price;
}
private:
string name;
int price;
};
// 订单类
class Order {
public:
Order(Product product, int quantity) {
this->product = product;
this->quantity = quantity;
}
Product getProduct() {
return product;
}
int getQuantity() {
return quantity;
}
int getTotalPrice() {
return product.getPrice() * quantity;
}
private:
Product product;
int quantity;
};
// 商品清单类
class ProductList {
public:
void addProduct(Product product) {
products.push_back(product);
}
int getProductCount() {
return products.size();
}
Product getProduct(int index) {
return products[index];
}
private:
vector<Product> products;
};
// 订单列表类
class OrderList {
public:
void addOrder(Order order) {
orders.push_back(order);
}
int getOrderCount() {
return orders.size();
}
Order getOrder(int index) {
return orders[index];
}
int getTotalPrice() {
int totalPrice = 0;
for (int i = 0; i < orders.size(); i++) {
totalPrice += orders[i].getTotalPrice();
}
return totalPrice;
}
private:
vector<Order> orders;
};
// 主函数
int main() {
// 创建商品清单
ProductList productList;
productList.addProduct(Product("苹果", 5));
productList.addProduct(Product("香蕉", 3));
productList.addProduct(Product("葡萄", 8));
productList.addProduct(Product("橙子", 4));
// 创建订单列表
OrderList orderList;
// 选择商品并下单
char choice;
do {
// 显示商品列表
cout << "商品列表:" << endl;
for (int i = 0; i < productList.getProductCount(); i++) {
cout << i + 1 << ". " << productList.getProduct(i).getName() << ",单价:" << productList.getProduct(i).getPrice() << "元" << endl;
}
// 选择商品
int productIndex;
cout << "请选择商品编号:";
cin >> productIndex;
// 输入数量
int quantity;
cout << "请输入购买数量:";
cin >> quantity;
// 添加订单
Order order(productList.getProduct(productIndex - 1), quantity);
orderList.addOrder(order);
// 继续下单?
cout << "是否继续下单?(Y/N)";
cin >> choice;
} while (choice == 'Y' || choice == 'y');
// 显示订单列表和总金额
cout << "您的订单列表:" << endl;
for (int i = 0; i < orderList.getOrderCount(); i++) {
Order order = orderList.getOrder(i);
cout << order.getProduct().getName() << " x " << order.getQuantity() << ",单价:" << order.getProduct().getPrice() << "元,小计:" << order.getTotalPrice() << "元" << endl;
}
cout << "总金额:" << orderList.getTotalPrice() << "元" << endl;
return 0;
}
```
以上代码实现了一个简单的商品订购系统,可以根据用户的选择添加订单,并显示订单列表和总金额。请注意,此代码示例仅供参考,实际应用中可能需要更复杂的功能和更严格的错误处理。
阅读全文