派生クラスの例
6661 ワード
15.7本の購入数が所定の制限を超えない場合、割引を受けるクラスを定義し、購入量が制限を超えると、超過した部分が原価で販売される.
Quote.h
Quote.cpp
main.cpp
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;
}