C++编程(D)

C 编程(D)

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ublic: void write(); }; 问题 class Receiver:public virtual Storable{ 解决方法是使用虚 public: void write(); }; 基类 Beijing University of Posts & Telecommunications Beijing [email protected] 15.2.4.1 用虚基类的程序设计 在为存在虚基类的类定义函数时,一般来 说,程序员并不知道这个基类是与其他派生 类共享的 在实现某种服务,其中要求调用基类的某个 函数恰好一次时,这种情况就可能引起问题 Beijing University of Posts & Telecommunications Beijing [email protected] 用虚基类的程序设计示例 class A{ /*...*/ }; // 无构造函数 class B{ public: B(); }; // 默认构造函数 class C{ public: C(int); }; // 无默认构造函数 class D:virtual public A, virtual public B, virtual public C{ D(){/*...*/} // 错误,没有调用C的构造函数 D(int i):C(i){/*...*/}; // ok }; 语言保证对于一个虚基类的构造函数将调用恰好一次 虚基类的构造函数将从最终派生类的构造函数里调用,而且要在派生 类的构造函数之前调用 Beijing University of Posts & Telecommunications Beijing [email protected] 用虚基类的程序设计示例 class Window{ // 拥有基本功能 virtual void draw(); }; class Window_with_border: public virtual Window{ // 边框功能 void own_draw(); // 显示边框 void draw(); }; class Window_with_menu: public virtual Window{ // 菜单功能 void own_draw(); // 显示菜单 void draw(); };// own_draw()不必是虚函数, 它只是被draw()调用,而draw()知 道调用哪一个 class Clock: public Window_with_border, public Window_with_menu { // 时钟功能 void own_draw(); void draw(); }; Beijing University of Posts & Telecommunications Beijing [email protected] 用虚基类的程序设计示例 void Window_with_border::draw(){ Window::draw(); own_draw(); } void Window_with_menu::draw(){ Window::draw(); own_draw(); } void Clock::draw(){ Window::draw(); Window_with_border::own_draw(); Window_with_menu::own_draw(); own_draw(); } Beijing University of Posts & Telecommunications Beijing 借助own_draw() 函数写出draw()函 数,可以使任何对 draw()的...
View Full Document

This note was uploaded on 02/10/2014 for the course ECE C++ taught by Professor Xiaoshengtang during the Fall '13 term at BUPT.

Ask a homework question - tutors are online