#include <iostream>
#include <string>
using namespace std;
class Item_base
{
public:
Item_base(const string &book = "", double sales_price = 0.0) :
isbn(book), price(sales_price) {}
string book() const
{
return isbn;
}
//如果去掉virtual,则print_total只调用基类net_price函数
virtual double net_price(size_t n) const
{
cout << "我是基类" << endl;
return n * price;
}
void print_total(ostream &os, const Item_base &item, size_t n)
{
os << "isbn: " << item.book() << endl;
os << "number: " << n << endl;
os << "total price: " << item.net_price(n) << endl << endl;
}
virtual ~Item_base() {}
private:
string isbn;
protected:
double price;
};
//有限折扣类
class Lds_item : public Item_base {
public:
//构造函数
Lds_item(const std::string& book = "",
double sales_price = 0.0,
size_t qty = 0, double disc_rate = 0.0):
Item_base(book, sales_price), //调用基类构造函数
max_qty(qty), discount(disc_rate) { }
//重定义基类版本以实现有限折扣策略
//对低于上限的购书量使用折扣价格
double Lds_item::net_price(size_t cnt) const
{
cout << "我是派生类" << endl;
if (cnt <= max_qty)
return cnt * (1 - discount) * price;
else
return cnt * price - max_qty * discount * price;
}
private:
size_t max_qty; // 可打折的购书量上限
double discount; // 折扣率
};
int main()
{
Item_base base("c++", 10);
Lds_item derived("primer", 20, 3, 0.2);
base.print_total(cout, base, 10);
base.print_total(cout, derived, 10);
return 0;
}