练习15.15
定义你自己的Disc_quote和Bulk_quote。
解答:
这里,就参考书中的实现吧。可以在这两个类中再添一些自己喜欢的内容。
后面的习题用书中的实现来做。
练习15.16
改写你在15.2.2节(第533页)练习中编写的数量受限的折扣策略,令其继承Disc_quote.
解答:
这里其实就是实现Bulk_quote类中的net_price函数。
#include <iostream>
#include <string>
using namespace std;
class Quote {
public:
Quote() = default;
Quote(const std::string &book, double sales_price):
bookNo(book), price(sales_price) { }
virtual ~Quote() = default; // dynamic binding for the destructor
std::string isbn() const { return bookNo; }
virtual double net_price(std::size_t n) const { return n * price; }
virtual void debug();
private:
std::string bookNo; // ISBN number of this item
protected:
double price = 0.0; // normal, undiscounted price
};
void Quote::debug(){
std::cout << "bookNo : " << bookNo << std::endl;
std::cout << "price : " << price << std::endl;
}
class Disc_quote : public Quote{
public:
Disc_quote() = default;
Disc_quote(const string& book, double price, size_t qty, double disc):
Quote(book, price), quantity(qty), discount(disc){}
double net_price(size_t) const = 0;
protected:
size_t quantity = 0;
double discount = 0.0;
};
class Bulk_quote : public Disc_quote{
public:
Bulk_quote() = default;
Bulk_quote(const string& book, double price, size_t qty, double disc):
Disc_quote(book, price, qty, disc){}
double net_price(size_t) const override;
};
double Bulk_quote::net_price(size_t cnt) const{
if (cnt > quantity){
return quantity * discount * price + (cnt - quantity) * price;
} else {
return cnt * discount * price;
}
}
double print_total(ostream &os, const Disc_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(){
Bulk_quote bulk("book", 20, 10, 0.5);
print_total(std::cout, bulk, 12);
print_total(std::cout, bulk, 10);
print_total(std::cout, bulk, 2);
}
练习15.17
尝试顶一个Dis_quote的对象,看看编译器给出的错误信息是什么?
解答:
这是g++4.9.1给出的错误提示
test.cpp: In function ‘int main()’:
test.cpp:70:14: error: cannot declare variable ‘test’ to be of abstract type ‘Disc_quote’
Disc_quote test;
^
test.cpp:30:7: note: because the following virtual functions are pure within ‘Disc_quote’:
class Disc_quote : public Quote{
^
test.cpp:35:10: note: virtual double Disc_quote::net_price(size_t) const
double net_price(size_t) const = 0;
^
VS2013
1> “double Disc_quote::net_price(size_t) const”: 是抽象的
clang 3.4
test.cpp:65:16: error: variable type 'Disc_quote' is an abstract class
Disc_quote test;
^
test.cpp:35:16: note: unimplemented pure virtual method 'net_price' in
'Disc_quote'
double net_price(size_t) const = 0;
^
1 error generated.