c++ 写一个电子商城
时间: 2023-07-29 19:13:16 浏览: 49
当然可以!以下是一个简单的示例,展示了如何使用C++编写一个简单的电子商城程序:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Product {
public:
string name;
double price;
int quantity;
Product(string name, double price, int quantity) {
this->name = name;
this->price = price;
this->quantity = quantity;
}
};
class ShoppingCart {
public:
vector<Product> products;
void addProduct(Product product) {
products.push_back(product);
}
void checkout() {
double total = 0.0;
cout << "=== Shopping Cart ===" << endl;
for (const auto& product : products) {
cout << product.name << " - $" << product.price << endl;
total += product.price;
}
cout << "Total: $" << total << endl;
}
};
int main() {
ShoppingCart cart;
Product p1("Product 1", 10.99, 2);
Product p2("Product 2", 19.99, 1);
cart.addProduct(p1);
cart.addProduct(p2);
cart.checkout();
return 0;
}
```
这个示例中,我们定义了两个类:`Product`代表一个产品,包含名称、价格和数量等属性;`ShoppingCart`代表购物车,包含一个产品列表,并提供添加产品和结账的功能。
在`main`函数中,我们创建了一个购物车对象`cart`,然后创建了两个产品对象`p1`和`p2`,并将它们添加到购物车中。最后,调用`cart.checkout()`方法,输出购物车中的产品列表和总价。
请注意,这只是一个简单的示例,实际开发中可能需要更复杂的功能和逻辑。希望这个示例能帮助你开始编写你自己的电子商城程序!
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)