Quote.h
#ifndef QUOTE_H
#define QUOTE_H
#include <iostream>
#include <string>
using namespace std;
//定义Quote类
class Quote{
double print_total(ostream &os,const Quote &item,size_t n);
public:
Quote();
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 ~Quote();
private:
string bookNo;
protected:
double price;
};
double print_total(ostream &os,const Quote &item,size_t n)
{
//这里是关键,n通过print_total(cout,quote,20),把对象quote的n值设置为20
//并通过print_total函数里面的语句item.net_price(n),执行各个基类或者派生类的net_price(n)函数
//并返回一个计算后的值并赋给ret,然后打印出ret,即最后的结果
double ret=item.net_price(n);
os<<"ISBN: "<<item.isbn()<<" #sold: "<< n <<" total due: "<<ret<<endl;
return ret;
}
//****************************************************************
//定义Bulk_quote类
class Bulk_quote:public Quote{
public:
//默认构造函数
Bulk_quote();
//构造函数
Bulk_quote(const string &book,double sales_price,size_t qty,double disc):
Quote(book,sales_price),min_qty(qty),discount(disc) { }
double net_price(size_t qty) const override
{
if(qty<min_qty)
return qty*price;
else
return qty*(1-discount)*price;
}
private:
size_t min_qty;
double discount;
};
//****************************************************************
//定义Number_quote类
class Number_quote:public Quote{
public:
Number_quote();
Number_quote(const string &book,double sales_price,size_t qty,double disc):
Quote(book,sales_price),max_qty(qty),discount(disc) { }
double net_price(size_t qty) const override
{
if (qty>=max_qty)
return max_qty*price*(1-discount)+(qty-max_qty)*price;
else
return qty*price*(1-discount);
}
private:
size_t max_qty;
double discount;
};
#endif QUOTE_H
Quote.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include "Quote.h"
using namespace std;
int main(){
Quote quote("基类书",50.0);
Bulk_quote bulk(string("派生类书"),25.0,15,0.2);
Number_quote pass(string("超出类书"),30.0,15,0.2);
print_total(cout,quote,20);
print_total(cout,bulk,20);
print_total(cout,pass,20);
system("pause");
return 0;
}