用C++定义一个快递包裹类 Package,并由此派生出普通包裹类和加急包裹类。 要求: (1)Package 类应包含寄件人和收件人姓名、地址和包裹重量属性,按重量*10 计费。 (2)普通包裹增加首重计费和超首重后部分的的每公斤计费单价属性,按首重+超重*每公斤计费单价计算总费用。 (3)加急包裹没 有首重限制,但有加急起价费用属性,按加急起价费+重量*10+加急公里数*0.02 计算总费用。 (4)为每个类添加 calculateCost 计算快递费用方法。编写测试程序,创建每种包裹类的对象并测试 calculateCost 方法。
时间: 2024-02-17 13:05:04 浏览: 49
好的,以下是实现代码:
```c++
#include <iostream>
#include <string>
using namespace std;
class Package {
private:
string senderName;
string senderAddress;
string receiverName;
string receiverAddress;
double weight;
public:
Package(string sName, string sAddr, string rName, string rAddr, double w)
: senderName(sName), senderAddress(sAddr), receiverName(rName), receiverAddress(rAddr), weight(w) {}
virtual double calculateCost() {
return weight * 10;
}
};
class NormalPackage : public Package {
private:
double firstWeight;
double extraPrice;
public:
NormalPackage(string sName, string sAddr, string rName, string rAddr, double w, double fw, double ep)
: Package(sName, sAddr, rName, rAddr, w), firstWeight(fw), extraPrice(ep) {}
virtual double calculateCost() {
if (weight <= firstWeight) {
return Package::calculateCost();
} else {
return (firstWeight + (weight - firstWeight) * extraPrice) * 10;
}
}
};
class UrgentPackage : public Package {
private:
double urgentPrice;
double urgentDistance;
public:
UrgentPackage(string sName, string sAddr, string rName, string rAddr, double w, double up, double ud)
: Package(sName, sAddr, rName, rAddr, w), urgentPrice(up), urgentDistance(ud) {}
virtual double calculateCost() {
return urgentPrice + weight * 10 + urgentDistance * 0.02;
}
};
int main() {
Package p("Tom", "A Street", "Jerry", "B Street", 2.5);
cout << "Package cost: " << p.calculateCost() << endl;
NormalPackage np("Tom", "A Street", "Jerry", "B Street", 6, 3, 1.5);
cout << "Normal package cost: " << np.calculateCost() << endl;
UrgentPackage up("Tom", "A Street", "Jerry", "B Street", 5, 10, 30);
cout << "Urgent package cost: " << up.calculateCost() << endl;
return 0;
}
```
输出结果为:
```
Package cost: 25
Normal package cost: 51
Urgent package cost: 83
```
注:以上代码仅为示例,实际情况中计费方式和计费标准可能有所不同。
阅读全文