标签:
OS:Windows 7
关键字:VS2012,C++,VTable,虚表
1.创建一个Win32控制台应用程序代码如下:
#include "stdafx.h" #include <string> #include <iostream> class A { public: virtual std::string AName(){return "A";} }; class B { public: virtual std::string BName(){return "B";} }; class C : public A, public B { public: virtual std::string BName(){return "C";} }; int _tmain(int argc, _TCHAR* argv[]) { C* pC = new C(); C* pC1 = new C(); std::cout<<pC->BName()<<std::endl; B* pB = static_cast<B*>(pC); std::cout<<pB->BName()<<std::endl; //A* pA = static_cast<A*>(pB); A* pA = dynamic_cast<A*>(pB); std::cout<<pA->AName()<<std::endl; A* pA1 = reinterpret_cast<A*>(pB); std::cout<<pA1->AName()<<std::endl; return 0; }
2.编译运行,控制台输出结果如下:
C
C
A
C
看到这个结果有没有让你奇怪的地方?为什么“pA1->AName()”输出是C?
3.在Watch窗口里看到的虚表结构如下:
总结如下:
标签:
原文地址:http://www.cnblogs.com/ldlchina/p/4482211.html