第十五章 面向对象程序设计

Posted GGBeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第十五章 面向对象程序设计相关的知识,希望对你有一定的参考价值。

15.1

虚函数:基类的成员函数,并在其前面添加关键字virtual,此类函数是基类希望其派生类进行覆盖的函数

 

15.2

protected:对应受保护成员,派生类可以访问该成员,但其他用户则禁止访问该成员

 

15.3

技术分享
 1 class Quote {
 2 public:
 3     Quote() = default;
 4     Quote(const string &book, double sales_price): bookNo(book), price(sales_price) {}
 5     string isbn() const { return bookNo; }
 6     virtual double net_price(size_t n) const { return n * price; }
 7     virtual ~Quote() = default;
 8 private:
 9     string bookNo;
10 protected:
11     double price = 0.0; 
12 };
13 
14 double print_total(ostream &os, const Quote &item, size_t n)
15 {
16     double ret = item.net_price(n);
17     os << "ISBN: " << item.isbn() << " # sold: " << n << " total due: " << ret << endl;
18     return ret; 
19 }
View Code

 

 

15.4

(a):错误,不可以继承自己

(b):正确

(c):错误,派生类的声明不需要包含它的派生列表

 

15.5

class Bulk_quote : public Quote {
public:
	Bulk_quote() = default;
	Bulk_quote(const string &book, double sales_price, size_t n, double dis): Quote(book, sales_price), min_qty(n), discount(dis) {}
	double net_price(size_t n) const override;
private:
	size_t min_qty = 0;
	double discount = 0.0;
};

double Bulk_quote::net_price(size_t n) const
{
	if (n >= min_qty)
		return n * (1 - discount) * price;
	else
		return n * price;
}

15.6

技术分享
 1 #include <iostream>
 2 #include <string>
 3  
 4 using namespace std;
 5 
 6 class Quote {
 7 public:
 8     Quote() = default;
 9     Quote(const string &book, double sales_price): bookNo(book), price(sales_price) {}
10     string isbn() const { return bookNo; }
11     virtual double net_price(size_t n) const { return n * price; }
12     virtual ~Quote() = default;
13 private:
14     string bookNo;
15 protected:
16     double price = 0.0; 
17 };
18 
19 class Bulk_quote : public Quote {
20 public:
21     Bulk_quote() = default;
22     Bulk_quote(const string &book, double sales_price, size_t n, double dis): Quote(book, sales_price), min_qty(n), discount(dis) {}
23     double net_price(size_t n) const override;
24 private:
25     size_t min_qty = 0;
26     double discount = 0.0;
27 };
28 
29 double Bulk_quote::net_price(size_t n) const
30 {
31     if (n >= min_qty)
32         return n * (1 - discount) * price;
33     else
34         return n * price;
35 }
36 
37 double print_total(ostream &os, const Quote &item, size_t n)
38 {
39     double ret = item.net_price(n);
40     os << "ISBN: " << item.isbn() << " # sold: " << n << " total due: " << ret << endl;
41     return ret; 
42 }
43 
44 
45 int main()
46 {
47     Quote book("3-298-15-2", 37.0);
48     Bulk_quote book2("3-298-15-2", 37.0, 5, 0.2);
49     print_total(cout, book2, 1);
50     print_total(cout, book2, 5);
51     print_total(cout, book, 5);
52     return 0; 
53 }
View Code

 

以上是关于第十五章 面向对象程序设计的主要内容,如果未能解决你的问题,请参考以下文章

Java第十五章Annotation注释

包子学系列——Java基础第十五章_Java反射机制

第十五章 软件架构之设计模式——单例模式

Java(第十五章)

java(第十五章)

java(第十五章)