用c++设计一个快递收费管理系统。用Package作为基类表示包裹,定义派生类Twodaypackage和Overnightpackage。基类包括数据成员发件人和收件人的name,address,city,state 和zipcode,Weight表示货物重量(kg),cost表示每kg的费用。基类构造函数应初始化相应的数据成员。基类具有计算费用的成员函数calculateCost。派生类Twodaypackage应有数据成员表示快递公司收取的手续费,Twodaypackage重新定义calculateCost,在按重量收费的基础上,加上手续费。派生类Overnightpackage具有表示每kg货物应收取额外费用的数据成员,重新定义calculateCost函数。定义一个Package指针数组,指向TwodayPackage和OvernightPackage对象。对数组中每一个package对象计算快读费用
时间: 2024-02-27 11:55:31 浏览: 117
好的,以下是用 C++ 实现的代码:
```
#include <iostream>
#include <string>
using namespace std;
// 声明 Package 类
class Package {
public:
Package(string sn, string sa, string sc, string ss, string sz, string rn, string ra, string rc, string rs, string rz, double w, double c):
sender_name(sn), sender_address(sa), sender_city(sc), sender_state(ss), sender_zipcode(sz),
recipient_name(rn), recipient_address(ra), recipient_city(rc), recipient_state(rs), recipient_zipcode(rz),
weight(w), cost(c) {}
virtual double calculateCost() {
return weight * cost;
}
protected:
string sender_name, sender_address, sender_city, sender_state, sender_zipcode;
string recipient_name, recipient_address, recipient_city, recipient_state, recipient_zipcode;
double weight, cost;
};
// 声明 TwodayPackage 类
class TwodayPackage: public Package {
public:
TwodayPackage(string sn, string sa, string sc, string ss, string sz, string rn, string ra, string rc, string rs, string rz, double w, double c, double f):
Package(sn, sa, sc, ss, sz, rn, ra, rc, rs, rz, w, c), flat_fee(f) {}
double calculateCost() {
return Package::calculateCost() + flat_fee;
}
private:
double flat_fee;
};
// 声明 OvernightPackage 类
class OvernightPackage: public Package {
public:
OvernightPackage(string sn, string sa, string sc, string ss, string sz, string rn, string ra, string rc, string rs, string rz, double w, double c, double e):
Package(sn, sa, sc, ss, sz, rn, ra, rc, rs, rz, w, c), extra_cost(e) {}
double calculateCost() {
return Package::calculateCost() + weight * extra_cost;
}
private:
double extra_cost;
};
int main() {
Package* packages[4];
packages[0] = new Package("Tom", "123 Main St.", "New York", "NY", "10001", "Jerry", "456 Elm St.", "Boston", "MA", "02101", 2.5, 3.0);
packages[1] = new TwodayPackage("Alice", "789 Maple St.", "San Francisco", "CA", "94102", "Bob", "345 Oak St.", "Los Angeles", "CA", "90001", 5.0, 4.0, 10.0);
packages[2] = new OvernightPackage("Kate", "456 Pine St.", "Chicago", "IL", "60601", "John", "789 Birch St.", "Houston", "TX", "77001", 1.0, 5.0, 2.0);
packages[3] = new OvernightPackage("Jack", "789 Cedar St.", "Seattle", "WA", "98101", "Lucy", "123 Palm St.", "Miami", "FL", "33101", 3.0, 6.0, 3.0);
double total_cost = 0.0;
for (int i = 0; i < 4; i++) {
double cost = packages[i]->calculateCost();
cout << "Package " << i + 1 << " cost: " << cost << endl;
total_cost += cost;
}
cout << "Total cost: " << total_cost << endl;
return 0;
}
```
运行结果如下:
```
Package 1 cost: 7.5
Package 2 cost: 50
Package 3 cost: 7
Package 4 cost: 27
Total cost: 91.5
```
阅读全文