#include <iostream>
using std::cin; using std::cout; using std::cerr; using std::endl;
using std::ostream;
#include <string>
using std::string;
class Quote{
public:
Quote() = default;
Quote(const string &book, double sales_price) :
bookNo(book), price(sales_price) {};
string isbn() const { return bookNo;}
//返回给定数量的书籍的销售总额
//派生类负责改写并使用不同的折扣计算算法
virtual double net_price(size_t n) const { return n * price;};
virtual ostream &debug(ostream &os) const {
os << "Quote::bookNo : " << bookNo << "\n"
<< "Quote::price :" << price << endl;
return os;
}
virtual ~Quote() = default; //对析构函数进行动态绑定
private:
string bookNo; //书籍的ISBN编号
protected:
double price = 0.0; //代表普通状态下不打折的价格
};
//计算并打印销售给定数量的某种书籍所得的费用
double print_total(ostream &os, const Quote &item, size_t n){
//根据传入item形参的对象类型调用Quote::net_price
//或者Bulk_quote::net_price
double ret = item.net_price(n);
os << "ISBN: " << item.isbn() //调用Quote::isbn()
<< " # sold: " << n << " total due: " << ret << endl;
return ret;
}
class Bulk_quote : public Quote{ //Bulk_quote继承自Quote
public:
Bulk_quote() = default;
Bulk_quote(const string &book, double p, size_t qty, double disc) :
Quote(book, p), min_qty(qty), discount(disc) {};
//覆盖基类的函数版本以实现基于大量购买的折扣政策
double net_price(size_t) const override;
private:
size_t min_qty = 0; //适用折扣政策的最低购买量
double discount = 0.0; //以小数表示的折扣额
};
//如果达到了购买书籍的某个最低限量值,就可以享受折扣价格了
double Bulk_quote::net_price(size_t cnt) const {
if (cnt > min_qty)
return cnt * (1 - discount) * price;
else
return cnt * price;
}
class L_Bulk_quote : public Quote{
public:
L_Bulk_quote() = default;
L_Bulk_quote(const string &book, double p, size_t qty, double disc) :
Quote(book, p), max_qty(qty), discount(disc) {};
double net_price(size_t) const override;
private:
size_t max_qty = 0;
double discount = 0;
};
double L_Bulk_quote::net_price(size_t cnt) const {
if (cnt <= max_qty)
return cnt * (1 - discount) * price;
else
return (cnt - max_qty) * price + max_qty * (1 - discount) * price;
}
int main(){
Quote basic("978-7-121-15535-2", 128.00);
Bulk_quote bulk("978-7-121-15535-2", 128.00, 100, 0.3);
L_Bulk_quote l_bulk("978-7-121-15535-2", 128.00, 150, 0.3);
print_total(cout, basic, 20);
print_total(cout, bulk, 120);
print_total(cout, l_bulk, 200);
}