现在的位置: 首页 > 综合 > 正文

纯虚函数中vtable的作用演示

2012年10月14日 ⁄ 综合 ⁄ 共 1682字 ⁄ 字号 评论关闭

 

源代码如下:

//

// Iface.cpp

// To compile, use: cl Iface.cpp

// date: 20090629

//author: Minrongf

#include <iostream.h>

#include <objbase.h>   // Define interface.

void trace(const char* pMsg) {cout << pMsg << endl ;}

 

// Abstract interfaces

interface IX

{

       virtual void __stdcall Fx1() = 0 ;

       virtual void __stdcall Fx2() = 0 ;

} ;

interface IY

{

       virtual void __stdcall Fy1() = 0 ;

       virtual void __stdcall Fy2() = 0 ;

} ;

// Interface implementation

class CA : public IX,

           public IY

{

public:

       // Implement interface IX.

       virtual void __stdcall Fx1() {cout << "CA::Fx1" << endl ;}

       virtual void __stdcall Fx2() {cout << "CA::Fx2" << endl ;}

 

       // Implement interface IY.

       virtual void __stdcall Fy1() {cout << "CA::Fy1" << endl ;}

       virtual void __stdcall Fy2() {cout << "CA::Fy2" << endl ;}

} ;

// Client

int main()

{

       trace("Client: Create an instance of the component.") ;

       CA* pA = new CA ;

       // Get an IX pointer.

       IX* pIX = pA ;

 

       trace("Client: Use the IX interface.") ;

       pIX->Fx1() ;

       pIX->Fx2() ;

 

       // Get an IY pointer.

       IY* pIY = pA ;

       trace("Client: Use the IY interface.") ;

       pIY->Fy1();

       pIY->Fy2();

 

       pIX = reinterpret_cast<IX*>(static_cast<IY*>(pA)) ; // notice cast

     //指针类型并不重要,vtable才决定了内部方法的功能.

       trace("Client: Use the IX interface to Call IY Function.") ;

       pIX->Fx1() ;

       pIX->Fx2() ;

 

       trace("Client: Delete the component.") ;

       delete pA ;

       return 0 ;

}

 

程序的输出为:

Client: Create an instance of the component.

Client: Use the IX interface.

CA::Fx1

CA::Fx2

Client: Use the IY interface.

CA::Fy1

CA::Fy2

Client: Use the IX interface to Call IY Function.

CA::Fy1

CA::Fy2

Client: Delete the component.

 

从上面的输出结果可以看到,当把IY接口强制转化为IX接口后,调用IX接口的函数,实际上是执行了IY接口的实现。从上面看到指针类型并不重要,vtable才决定了内部方法的功能,如果去掉IY接口的第一个函数,那么在把IY接口转为IX接口后,pIX->Fx1(),得输出是CA::Fy2,pIX->Fx2() 将会出现异常,这是因为IY的纯虚函数不存在了.

 

抱歉!评论已关闭.