练习15.15、练习15.16
1 #include <iostream> 2 #include <string> 3 #include <utility> 4 #include <memory> 5 #include <vector> 6 7 using namespace std; 8 9 class Quote { 10 public: 11 Quote() = default; 12 Quote(const string &book, double sales_price) : bookNo(book), price(sales_price) {} 13 const string& isbn() const { return bookNo; } 14 virtual double net_price(size_t n) const{ return n * price; } 15 virtual ~Quote() = default; 16 private: 17 string bookNo; 18 protected: 19 double price = 0.0; 20 }; 21 22 class Disc_quote : public Quote{ 23 public: 24 Disc_quote() = default; 25 Disc_quote(const string &book, double sales_price, size_t quan, double dis) : Quote(book, sales_price), quantity(quan), discount(dis) {} 26 double net_price(size_t n) const = 0; 27 protected: 28 size_t quantity = 0; 29 double discount = 0.0; 30 }; 31 32 class Bulk_quote : public Disc_quote { 33 public: 34 Bulk_quote() = default; 35 Bulk_quote(const string& book, double p, size_t qty, double disc) : Disc_quote(book, p, qty, disc) {} 36 double net_price(size_t n) const override; 37 }; 38 39 class lim_discount : public Disc_quote { 40 public: 41 lim_discount() = default; 42 lim_discount(const string& book, double p, size_t qty, double disc) : Disc_quote(book, p, qty, disc) {} 43 double net_price(size_t n) const override; 44 }; 45 46 double print_total(ostream& os, const Quote& item, size_t t); 47 48 int main() 49 { 50 Bulk_quote b1("C++ primer", 128.0, 10, 0.60); 51 lim_discount l1("C++ primer", 128.0, 20, 0.9); 52 print_total(cout, b1, 11); 53 print_total(cout, b1, 9); 54 print_total(cout, l1, 21); 55 print_total(cout, l1, 19); 56 system("pause"); 57 return 0; 58 } 59 60 double print_total(ostream & os, const Quote &item, size_t t) 61 { 62 double ret = item.net_price(t); 63 os << "ISBN: " << item.isbn() << " # sold: " << t << " total due: " << ret << endl; 64 return ret; 65 } 66 67 double Bulk_quote::net_price(size_t n) const 68 { 69 if (n >= quantity) 70 return n * (1 - discount) * price; 71 else 72 return n * price; 73 } 74 75 double lim_discount::net_price(size_t n) const 76 { 77 if (n <= quantity) 78 return n * (1 - discount) * price; 79 else 80 return Quote::net_price(n); 81 }
练习15.17
1>f:\c++projicets\project1\project1\源.cpp(56): error C2259: “Disc_quote”: 不能实例化抽象类
1> f:\c++projicets\project1\project1\源.cpp(56): note: 由于下列成员:
1> f:\c++projicets\project1\project1\源.cpp(56): note: “double Disc_quote::net_price(std::size_t) const”: 是抽象的
1> f:\c++projicets\project1\project1\源.cpp(26): note: 参见“Disc_quote::net_price”的声明
========== 生成: 成功 0 个,失败 1 个,最新 0 个,跳过 0 个 ==========
时间: 2024-10-17 04:28:23