15.7定义一个类使其实现一种数量受限的折扣策略,具体策略是:当购买书籍的数量不超过一个给定的限量时享受折扣,如果购买量一旦超过了限量,则超出的部分将以原价销售。
Quote.h
#ifndef QUOTE_H #define QUOTE_H #include<iostream> #include<string> using namespace std; 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 ~Quote()=default; private: string bookNo; protected: double price=0.0; }; class Bulk_quote:public Quote { public: Bulk_quote()=default; Bulk_quote(const string &, double , size_t , double ); double net_price(size_t) const override; private: size_t min_qty=0; double discount=0.0; }; #endif // QUOTE_H
Quote.cpp
#include"Quote.h" Bulk_quote::Bulk_quote(const string &book, double p, size_t qty, double disc):Quote(book,p),min_qty(qty),discount(disc) {} double Bulk_quote::net_price(size_t cnt) const { if(cnt<=min_qty) return cnt*(1-discount)*price; else return (cnt-min_qty)*price+min_qty*(1-discount)*price; }
main.cpp
#include <iostream> #include"Quote.h" using namespace std; double print_total(ostream &os,const Quote &item,size_t n) { double ret=item.net_price(n); os<<"ISBN: "<<item.isbn()<<" # sold: "<<n<<" total due: "<<ret<<endl; return ret; } int main() { Quote quote("Base",2); Bulk_quote bulk("devired",2,5,0.5); print_total(cout,quote,6); print_total(cout,bulk,6); return 0; }
时间: 2024-10-07 06:21:51