定义抽象类 Iotion ,其中有三个函数: Price ()、 Amount ()和纯虚函数 Show (),在此基类的基础上派生出 Basketball (表示篮球)和 Volleyball 类(表示排球),这两个类都将 lotion 声明为虚基类且都由 Price ()函数输入球的价格,由 Amount ()函数输入球的个数,都由虚函数 Show ()计算并显示实际金额。球的实 T 际金额=金额+数量。在主函数中分别声明对象并输入价格和各自的数量;通过对象调用相应的函数求两类球的实际应付金额,并在主函数中定义 Motion 类的对象指针来输出两类球的实际应付金额的信息。(提示:每个篮球50元需要购买 100个,每个排球60元需要购买40个,运行效果如下) 焖头篮球的价格和数量: 50100 购买篮球的价格为:50,数量为:100,总价格为:5000请输入购买排球的价格和数量: 40 买排球的价格为:60,数量为:40,总价格为:2400
时间: 2024-03-16 14:41:43 浏览: 10
以下是代码实现:
```
#include <iostream>
using namespace std;
class Lotion {
public:
virtual float Price() = 0;
virtual int Amount() = 0;
virtual void Show() = 0;
};
class Basketball : virtual public Lotion {
public:
Basketball(float p, int a) : price(p), amount(a) {}
float Price() {
return price;
}
int Amount() {
return amount;
}
void Show() {
cout << "购买篮球的价格为:" << price << ",数量为:" << amount << ",总价格为:" << price * amount << endl;
}
protected:
float price;
int amount;
};
class Volleyball : virtual public Lotion {
public:
Volleyball(float p, int a) : price(p), amount(a) {}
float Price() {
return price;
}
int Amount() {
return amount;
}
void Show() {
cout << "购买排球的价格为:" << price << ",数量为:" << amount << ",总价格为:" << price * amount << endl;
}
protected:
float price;
int amount;
};
int main() {
float price;
int amount;
cout << "篮球的价格和数量:";
cin >> price >> amount;
Basketball b(price, amount);
b.Show();
cout << "排球的价格和数量:";
cin >> price >> amount;
Volleyball v(price, amount);
v.Show();
Lotion* p;
p = &b;
cout << "篮球实际应付金额:" << p->Price() * p->Amount() << endl;
p = &v;
cout << "排球实际应付金额:" << p->Price() * p->Amount() << endl;
return 0;
}
```
程序输出如下:
```
篮球的价格和数量:50 100
购买篮球的价格为:50,数量为:100,总价格为:5000
排球的价格和数量:40 60
购买排球的价格为:40,数量为:60,总价格为:2400
篮球实际应付金额:5000
排球实际应付金额:2400
```