继承中类的作用域
Bulk_quote bulk;
cout<<bulk.isbn();class Disc_quote : public Quote{public:std::pair<size_t,double> discount_policy() const{ return {quantity,discount};}//其他成员与之前版本一致
};Bulk_quote bulk;
Bulk_quote *bulkP = &bulk; //静态类型与动态类型一致
Quote *itemP = &bulk; //静态类型与动态类型不一致
bulkP->discount_policy(); //正确:bulkP的类型是Bulk_quote*
itemP->discount_policy(); //错误:itemP的类型是Quote*
名字冲突与继承
struct Base{Base():mem(0){}protected:int mem;
};
struct Derived : Base{Derived(int i) : mem(i){} //用i初始化Derived::mem//Base::mem进行默认初始化int get_mem(){return mem;} //返回Derived::memprotected:int mem; //隐藏基类中的mem
};Derived d(42);
cout<<d.get_mem()<<endl; //打印42
派生类的成员将隐藏同名的基类成员
通过作用域运算符来使用隐藏的成员
struct Derived : Base{int get_base_mem(){return Base::mem;}
};
名字查找先于类型查找
struct Base{int memfcn();
};
struct Derived : Base{int memfcn(int); //隐藏基类的memfcn
};
Derived d;Base b;
b.memfcn(); //调用Base::memfcn
d.memfcn(10); //调用Derived::memfcn
d.memfcn(); //错误:参数列表为空的memfcn被隐藏了
d.Base::memfcn(); //正确:调用Base::memfcn