用C++写一个购物程序
时间: 2023-09-28 12:03:50 浏览: 45
好的,以下是一个简单的使用 C++ 编写的购物程序示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Product {
private:
string name;
double price;
public:
Product(string name, double price) {
this->name = name;
this->price = price;
}
string getName() {
return name;
}
double getPrice() {
return price;
}
};
class ShoppingCart {
private:
vector<Product> products;
public:
void addProduct(Product product) {
products.push_back(product);
}
double getTotalPrice() {
double total = 0;
for (int i = 0; i < products.size(); i++) {
total += products[i].getPrice();
}
return total;
}
void checkout() {
double total = getTotalPrice();
cout << "Total price: " << total << endl;
// 在这里添加付款的代码
}
};
int main() {
Product p1("Product 1", 5.99);
Product p2("Product 2", 9.99);
Product p3("Product 3", 15.99);
ShoppingCart cart;
cart.addProduct(p1);
cart.addProduct(p2);
cart.addProduct(p3);
cart.checkout();
return 0;
}
```
在上面的代码中,我们定义了两个类:`Product` 和 `ShoppingCart`。`Product` 表示一个商品,包含商品名称和价格两个属性,`ShoppingCart` 表示购物车,包含一个商品列表和一些购物车操作的方法。
在 `main` 函数中,我们创建了三个 `Product` 对象,然后将它们添加到一个 `ShoppingCart` 对象中。最后,我们调用 `checkout` 方法计算购物车中商品的总价并输出,你可以在 `checkout` 方法中添加付款的相关代码。
注意,这只是一个很简单的购物程序示例,实际的购物程序需要包含更多的功能,例如选择商品、添加到购物车、结算、付款等功能。