您的位置:首页 > 其它

关于虚拟函数的一些总结 (参考:深入浅出MFC 第二版 候俊杰)

2015-02-09 16:32 411 查看
关于虚拟函数实现多态的总结:

 

1)如果希望在派生类别中重新定义父类的某个函数,则在父类中必须将此函数设为虚拟函数;

 

2)抽象类别的虚拟函数一般不被调用,所以也不必被定义,将其设为纯虚函数;

 

3)在不使用虚拟函数的情况下,若用父类的指针指向某个派生类的对象,则使用该指针调用某个函数时,会调用指父类的函数;而使用虚拟函数,则会调用父类指针指向的派生类别的函数。因此,虚拟函数可以使得使用单一指令唤起不同函数,而非虚拟函数则只能根据指针的类型判断调用哪个类中的函数;

 

4)拥有纯虚拟函数的类别为抽象类别,不可以有具体对象实例,但能申明该抽象类别的指针;

 

5)虚拟函数被继承下去认为虚拟函数,且可以省略关键字virtual;

 

6)虚拟函数是实现多态和动态绑定的关键。编译器在编译时,无法判断究竟调用的是哪个虚拟函数,必须在执行的时候才能确定。

 

例子(摘自:深入浅出MFC 第二版 候俊杰):

  #0001 #include <iostream.h>

#0002 class CShape

#0003 {

#0004 public:

#0005 virtual void display() { cout << "Shape /n"; }

#0006 };

#0007 //------------------------------------------------

#0008 class CEllipse : public CShape

#0009 {

#0010 public:

#0011 virtual void display() { cout << "Ellipse /n"; }

#0012 };

#0013 //------------------------------------------------

#0014 class CCircle : public CEllipse

#0015 {

#0016 public:

#0017 virtual void display() { cout << "Circle /n"; }

#0018 };

#0019 //------------------------------------------------

#0020 class CTriangle : public CShape

#0021 {

#0022 public:

#0023 virtual void display() { cout << "Triangle /n"; }

#0024 };

不必设计复杂的串行函数如add 或getNext 才能验证这件事,我们看看下面这个简单例

子。如果我把职员一例中所有四个类别的computePay 函数前面都加上virtual 保留字,

使它们成为虚拟函数,那么:

现在重新回到Shape 例子,我打算让display 成为虚拟函数:

73

#0025 //------------------------------------------------

#0026 class CRect : public CShape

#0027 {

#0028 public:

#0029 virtual void display() { cout << "Rectangle /n"; }

#0030 };

#0031 //------------------------------------------------

#0032 class CSquare : public CRect

#0033 {

#0034 public:

#0035 virtual void display() { cout << "Square /n"; }

#0036 };

#0037 //------------------------------------------------

#0038 void main()

#0039 {

#0040 CShape aShape;

#0041 CEllipse aEllipse;

#0042 CCircle aCircle;

#0043 CTriangle aTriangle;

#0044 CRect aRect;

#0045 CSquare aSquare;

#0046 CShape* pShape[6] = { &aShape,

#0047    &aEllipse,

#0048    &aCircle,

#0049    &aTriangle,

#0050    &aRect,

#0051    &aSquare };

#0052

#0053 for (int i=0; i< 6; i++)

#0054 pShape[i]->display();

#0055 }

#0056 //------------------------------------------------

得到的結果是:

Shape

Ellipse

Circle

Triangle

Rectangle

Square
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: