用C++写一个商品的类并且调用
时间: 2024-05-18 13:15:20 浏览: 13
好的,我来为您展示一个简单的商品类的示例代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Commodity {
private:
string name; // 商品名称
double price; // 商品价格
int quantity; // 商品数量
public:
// 构造函数
Commodity() {
name = "";
price = 0.0;
quantity = 0;
}
Commodity(string n, double p, int q) {
name = n;
price = p;
quantity = q;
}
// 成员函数
void setName(string n) {
name = n;
}
void setPrice(double p) {
price = p;
}
void setQuantity(int q) {
quantity = q;
}
string getName() {
return name;
}
double getPrice() {
return price;
}
int getQuantity() {
return quantity;
}
double getTotalPrice() {
return price * quantity;
}
};
int main() {
Commodity c1("电视机", 2999.0, 2);
Commodity c2;
c2.setName("洗衣机");
c2.setPrice(1999.0);
c2.setQuantity(1);
cout << c1.getName() << " " << c1.getPrice() << " " << c1.getQuantity() << " " << c1.getTotalPrice() << endl;
cout << c2.getName() << " " << c2.getPrice() << " " << c2.getQuantity() << " " << c2.getTotalPrice() << endl;
return 0;
}
```
这个类中包含了商品的名称、价格和数量,并实现了一些基本的操作,比如设置和获取商品的属性,以及计算商品总价。在main函数中,我们创建了两个商品对象,并对它们进行了一些属性设置和调用商品类中的成员函数。运行这段代码,可以得到以下输出结果:
```
电视机 2999 2 5998
洗衣机 1999 1 1999
```
希望这个示例可以帮助到您。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)