导航

C++primer 练习15.15

Posted on 2016-04-17 01:16  CSU蛋李  阅读(150)  评论(0编辑  收藏  举报
// 15_15.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

class Quote
{
public:
    Quote() = default;
    Quote(const string &book,double p):bookNo(book),price(p){}
    const string& isbn()const { return bookNo; }
    virtual double net_price(size_t n)const
    {
        return n*price;
    }
private:
    string bookNo;
protected:
    double price = 0.0;
};

class Dis_Quote :public Quote
{
public:
    Dis_Quote() = default;
    Dis_Quote(const string &book,double p,size_t n,double d):Quote(book,p),quantity(n),discount(d){}
    virtual double net_price(size_t n)const = 0;
protected:
    size_t quantity = 0;
    double discount = 0.0;
};

class Bulk_Quote :public Dis_Quote
{
public:
    Bulk_Quote() = default;
    Bulk_Quote(const string &book,double p,size_t n,double d):Dis_Quote(book,p,n,d){}
    virtual double net_price(size_t n)const override
    {
        if (n > quantity)
            return n*(1 - discount)*price;
        else
            return n*price;
    }
};

class Exercise_Quote :public Dis_Quote
{
public:
    Exercise_Quote() = default;
    Exercise_Quote(const string &book,double p,size_t n,double d):Dis_Quote(book,p,n,d){}
    virtual double net_price(size_t n)const override
    {
        if (n <= quantity)
            return n*(1 - discount)*price;
        else
            return quantity*(1 - discount)*price + (n - quantity)*price;
    }
};

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 q1("lidandan", 5);
    Bulk_Quote q2("lidandan", 5, 9, 0.1);
    Exercise_Quote q3("lidandan", 5, 9, 0.1);
    //Dis_Quote q4;
    print_total(cout, q1, 10);
    print_total(cout, q2, 10);
    print_total(cout, q3, 10);
    return 0;
}