C++Primer——chapter15_OOP(1):派生类初涉

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值