编程题目:使用C++语言模拟完成一个简单的计算机系统 参考编程选择:模拟学生选课、超市购物、化妆品销售、城市公交车线路、健身俱乐部会员管理等,可以自由选择题材。
时间: 2023-08-14 13:05:48 浏览: 38
好的,我可以帮你设计一个简单的超市购物系统。首先,我们需要设计几个类:
1. 商品类(Product):包含商品编号、商品名称、商品价格等属性。
2. 购物车类(ShoppingCart):包含商品列表、总价格等属性和添加商品、删除商品、计算总价等方法。
3. 超市类(Supermarket):包含商品列表、购物车等属性和展示商品、添加商品到购物车、结算等方法。
下面是一个简单的实现:
```c++
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class Product {
public:
Product(int id, string name, double price) : id(id), name(name), price(price) {}
int getId() const {
return id;
}
string getName() const {
return name;
}
double getPrice() const {
return price;
}
private:
int id;
string name;
double price;
};
class ShoppingCart {
public:
void addProduct(const Product& product) {
products.push_back(product);
}
void removeProduct(int productId) {
for (auto it = products.begin(); it != products.end(); ++it) {
if (it->getId() == productId) {
products.erase(it);
break;
}
}
}
double getTotalPrice() const {
double totalPrice = 0;
for (const auto& product : products) {
totalPrice += product.getPrice();
}
return totalPrice;
}
void print() const {
cout << "Shopping Cart:" << endl;
for (const auto& product : products) {
cout << product.getName() << " - " << product.getPrice() << endl;
}
cout << "Total price: " << getTotalPrice() << endl;
}
private:
vector<Product> products;
};
class Supermarket {
public:
void addProduct(const Product& product) {
products.push_back(product);
}
void showProducts() const {
cout << "Products:" << endl;
for (const auto& product : products) {
cout << product.getId() << " - " << product.getName() << " - " << product.getPrice() << endl;
}
}
void addToCart(int productId, ShoppingCart& cart) {
for (const auto& product : products) {
if (product.getId() == productId) {
cart.addProduct(product);
cout << "Added " << product.getName() << " to shopping cart." << endl;
return;
}
}
cout << "Product not found." << endl;
}
void checkout(ShoppingCart& cart) {
cout << "Checkout:" << endl;
cart.print();
cart = ShoppingCart(); // clear cart
}
private:
vector<Product> products;
};
int main() {
Supermarket supermarket;
supermarket.addProduct(Product(1, "Apple", 2.5));
supermarket.addProduct(Product(2, "Banana", 3.0));
supermarket.addProduct(Product(3, "Orange", 2.0));
supermarket.addProduct(Product(4, "Grapes", 4.0));
supermarket.showProducts();
ShoppingCart cart;
supermarket.addToCart(1, cart);
supermarket.addToCart(2, cart);
cart.print();
supermarket.addToCart(5, cart);
supermarket.checkout(cart);
cart.print();
return 0;
}
```
这个程序实现了一个简单的超市购物系统,可以展示商品列表、将商品添加到购物车、结算购物车等功能。当然,这只是一个简单的示例,实际的超市购物系统可能需要更复杂的功能,例如库存管理、会员管理等等,这些功能可以根据需要进行扩展。