對(duì)于如下代碼:
//Base.cpp
#include<iostream>
using namespace std;
class Base
{
public :
Base(char xx) { x = xx; }
virtual void who()
{
cout << "Base class: " << x << "\n" ;
}
protected:
char x;
} ;
class First_d : public Base
{
public :
First_d(char xx, char yy):Base(xx)
{
y = yy;
}
void who()
{
cout << "First derived class: "<< x << ", " << y << "\n" ; }
protected:
char y;
} ;
class Second_d : public First_d
{
public :
Second_d( char xx, char yy, char zz ) : First_d( xx, yy )
{
z = zz;
}
void who()
{
cout << "Second derived class: "<< x << ", " << y << ", " << z << "\n" ;
}
protected:
char z;
} ;
void main()
{
Base B_obj( 'A' ) ;
First_d F_obj( 'T', 'O' ) ;
Second_d S_obj( 'E', 'N', 'D' ) ;
Base * p ;
p = & B_obj ; p -> who() ;
p = &F_obj ; p -> who() ;
p = &S_obj ; p -> who() ;
F_obj.who() ;
( ( Second_d * ) p ) -> who() ;
while(1);
}
我們注意到Base類中的void who()函數(shù)添加了關(guān)鍵字virtual
上述代碼塊運(yùn)行結(jié)果如下:
Base class: A
First derived class: T, O
Second derived class: E, N, D
First derived class: T, O
Second derived class: E, N, D
假如去掉who()前的關(guān)鍵字virtual,運(yùn)行結(jié)果會(huì)變?yōu)椋?/p>
Base class: A
Base class: T
Base class: E
First derived class: T, O
Second derived class: E, N, D
發(fā)生這樣的情況的關(guān)鍵是:virtual關(guān)鍵字使得 隨著p指向不同對(duì)象,this指針作類型轉(zhuǎn)換執(zhí)行不同實(shí)現(xiàn)版本
溫馨提示:
- 一個(gè)虛函數(shù),在派生類層界面相同的重載函數(shù)都保持虛特性
- 虛函數(shù)必須是類的成員函數(shù)
- 不能將友員說明為虛函數(shù),但虛函數(shù)可以是另一個(gè)類的友員
- 析構(gòu)函數(shù)可以是虛函數(shù),但構(gòu)造函數(shù)不能是虛函數(shù)
- 在派生類中重載基類的虛函數(shù)要求函數(shù)名、返回類型、參數(shù)個(gè)數(shù)、
參數(shù)類型和順序完全相同 - 如果僅僅返回類型不同,C++認(rèn)為是錯(cuò)誤重載
- 如果函數(shù)原型不同,僅函數(shù)名相同,丟失虛特性