在类中被声明为virtual的成员,基类希望这种成员能被派生类重定义
除了构造函数外,所有非static成员都可以是虚成员
基类希望派生类有权访问而禁止其他用户访问的成员定义为protected
private只能被基类的成员和友元访问,派生类也不能访问
class Quote
{
public:
Quote()=default;
Quote(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;
};
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;
}
(a)不能继承自己
(b)正确
(c)声明类时不应包含派生列表
class Bulk_Quote : public Quote
{
public:
Bulk_Quote() = default;
Bulk_Quote(const string &book, double sales_price, size_t mq, double disc)
: Quote(book, sales_price), min_qty(mq), discount(disc) {
}
double net_price(size_t cnt) const override
{
if (cnt >= min_qty)
return cnt * (1 - discount) * price;
else
return cnt * price;
}
private:
size_t min_qty;
double discount;
};
class Limited_Quote : public Quote
{
public:
Limited_Quote() = default;
Limited_Quote(const string &book, double sales_price, size_t cnt, double dis) : Quote(book, sales_price), min_qty(cnt), discount(dis) {
}
double net_price(size_t n) const override
{
if (n <= min_qty)
return n * (1 - discount) * price;
else
return min_qty * (1 - discount) * price + (n - min_qty) * price;
}
private:
size_t min_qty;
double discount;
};
静态类型在编译时已知,它是变量声明时的类型
动态类型只有运行时才知道,是变量表示的内存中的对象的类型
Bulk_Quote bulk;
double print_total(..., const Quote &item, ...);
Quote *pQuote = &bulk;
Quote &rQuote = bulk;
print_total(..., bulk, ...);
在要求基类的地方使用了派生类,是静态类型和动态类型不同的典型例子
class Quote
{
publ