荔园在线

荔园之美,在春之萌芽,在夏之绽放,在秋之收获,在冬之沉淀

[回到开始] [上一篇][下一篇]


发信人: FDISK (FDISK-C), 信区: Program
标  题: [转载] 关于virtual函数
发信站: BBS 荔园晨风站 (Tue Dec 21 17:48:48 1999), 转信


下面这段程序来自<<Thinking in C++>>

//: C15:Wind3.cpp
// Late binding with virtual
#include <iostream>
using namespace std;
enum note { middleC, Csharp, Cflat }; // Etc.

class Instrument {
public:
  virtual void play(note) const {
    cout << "Instrument::play" << endl;
  }
};

// Wind objects are Instruments
// because they have the same interface:
class Wind : public Instrument {
public:
  // Redefine interface function:
  void play(note) const {
    cout << "Wind::play" << endl;
  }
};

void tune(Instrument& i) {
  // ...
  i.play(middleC);
}

int main() {
  Wind flute;   // 派生类
  tune(flute); // Upcasting 在C中这个是不允许的, 但在
               // C++中却是一个特性. 它保证你使用的play()
               // 是Wind中的.
} ///:~

运行输出: Wind::play

    从上面的程序可以看出virtual的好处. 你一开始在基类里面声明
了一个virtual函数, 那么以后你要扩展基类的功能就非常方便了. 上
面的例子中, 为了调用派生类中的play()函数, 你无需再定义一个
void tune(Wind & i)
{
        i.play(middleC);
}
    因为虚拟函数机制保证了你调用的就是Wind派生类里面的play()函数.

--
※ 修改:·FDISK 於 Dec 21 17:50:24 修改本文·[FROM: 192.168.1.242]
※ 来源:·BBS 荔园晨风站 bbs.szu.edu.cn·[FROM: 192.168.1.242]


[回到开始] [上一篇][下一篇]

荔园在线首页 友情链接:深圳大学 深大招生 荔园晨风BBS S-Term软件 网络书店