C++ 虚函数表解析——转自陈皓

http://blog.csdn.net/haoel

C++ 虚函数表解析 - 陈皓专栏 【空谷幽兰,心如皓月】 - 博客频道 - CSDN.NET
http://blog.csdn.net/haoel/article/details/1948051/

 

#include<iostream>

using namespace std;



//基类

class Base {

public:

	virtual void f() { cout << "Base::f" << endl; }

	virtual void g() { cout << "Base::g" << endl; }

	virtual void h() { cout << "Base::h" << endl; }



};



//无虚函数覆盖的子类

class derive:public Base

{

	virtual void f1() { cout << "derive::f1" << endl; }

	virtual void g1() { cout << "derive::g1" << endl; }

	virtual void h1() { cout << "derive::h1" << endl; }

};



//有虚函数覆盖

class derive2:public Base

{

	virtual void f() { cout << "derive2::f" << endl; }

	virtual void g() { cout << "derive2::g" << endl; }

	virtual void h() { cout << "derive2::h" << endl; }

};



int main()

{

	//基类里虚函数

	/*

	typedef void(*Fun)(void);//表示定义一个函数指针类型

	Base b;

	Fun pFun = NULL;

	cout << "虚函数表地址:" << (int*)(&b) << endl;

	cout << "虚函数表 — 第一个函数地址:" << (int*)*(int*)(&b) << endl;

	// Invoke the first virtual function 

	pFun = (Fun)*((int*)*(int*)(&b));//加上后面的(Fun)*是将int*强制转换为函数指针

	pFun();

	*/



	//无虚函数覆盖

	/*

	typedef void(*Fun)(void);

	derive c;

	Fun pFun=NULL;

	cout<<(int*)*(int*)(&c)+0<<endl;

	pFun=(Fun)*((int*)*(int*)(&c)+0);

	pFun();

	cout<<(int*)*(int*)(&c)+1<<endl;

	pFun=(Fun)*((int*)*(int*)(&c)+1);

	pFun();

	cout<<(int*)*(int*)(&c)+2<<endl;

	pFun=(Fun)*((int*)*(int*)(&c)+2);

	pFun();

	cout<<(int*)*(int*)(&c)+3<<endl;

	pFun=(Fun)*((int*)*(int*)(&c)+3);

	pFun();

	*/



	//





	system("pause");

	return 1;

}

  

 

你可能感兴趣的:(C++)