某顾客到商店购买生活物品,购买:米5斤每斤2.4元,猪肉2斤每斤10元,油一壶50元,请设计一段程序实现顾客购物清单及总价的计算及显示,具体要求如下: (1)编写一个抽象类Goods,在public中包含两个纯虚函数goodsprice与show; (2)编写三个类rice、pork、oil,公共继承Goods类;且每个类都两个私有属性weight,price分别表示单位及单位价格,有一个私有goodsprice函数计算商品价格:weight*price;有一个公有函数show显示商品的价格; (3)编写一个total函数计算所有商品总价; (4)编写main函数显示所有商品的价格及总价。
时间: 2024-02-15 12:04:46 浏览: 17
好的,以下是代码实现:
```cpp
#include <iostream>
using namespace std;
// 声明抽象类Goods
class Goods {
public:
virtual float goodsprice() = 0; // 纯虚函数
virtual void show() = 0; // 纯虚函数
};
// 声明继承Goods的rice类
class Rice : public Goods {
private:
float weight;
float price;
public:
Rice(float w, float p) {
weight = w;
price = p;
}
float goodsprice() {
return weight * price;
}
void show() {
cout << "米 " << weight << "斤,单价 " << price << "元,总价 " << goodsprice() << "元" << endl;
}
};
// 声明继承Goods的pork类
class Pork : public Goods {
private:
float weight;
float price;
public:
Pork(float w, float p) {
weight = w;
price = p;
}
float goodsprice() {
return weight * price;
}
void show() {
cout << "猪肉 " << weight << "斤,单价 " << price << "元,总价 " << goodsprice() << "元" << endl;
}
};
// 声明继承Goods的oil类
class Oil : public Goods {
private:
float weight;
float price;
public:
Oil(float w, float p) {
weight = w;
price = p;
}
float goodsprice() {
return weight * price;
}
void show() {
cout << "油 " << weight << "壶,单价 " << price << "元,总价 " << goodsprice() << "元" << endl;
}
};
// 声明计算总价的total函数
float total(Goods* goods[], int n) {
float sum = 0;
for (int i = 0; i < n; i++) {
sum += goods[i]->goodsprice();
}
return sum;
}
// 主函数
int main() {
// 创建商品对象
Rice* rice = new Rice(5, 2.4);
Pork* pork = new Pork(2, 10);
Oil* oil = new Oil(1, 50);
// 显示商品价格
rice->show();
pork->show();
oil->show();
// 计算总价并显示
Goods* goods[] = { rice, pork, oil };
int n = sizeof(goods) / sizeof(Goods*);
cout << "总价为:" << total(goods, n) << "元" << endl;
return 0;
}
```
运行结果:
```
米 5斤,单价 2.4元,总价 12元
猪肉 2斤,单价 10元,总价 20元
油 1壶,单价 50元,总价 50元
总价为:82元
```