直接上代码
#include<stdio.h>
#include<iostream>
using std::endl;
using std::cout;
class Base
{
private:
/* data */
public:
Base(/* args */);
virtual
void print()
{
cout<<"hello "<<endl;
}
virtual
~Base();
};
Base::Base(/* args */)
{
cout<<"Base()"<<endl;
}
Base::~Base()
{
cout<<"~Base()"<<endl;
}
class Derived
:public Base
{
private:
/* data */
public:
Derived(/* args */);
void print() override
{
cout<<"world"<<endl;
}
~Derived();
};
Derived::Derived(/* args */)
{
cout<<"Derived()"<<endl;
}
Derived::~Derived()
{
cout<<"~Derived()"<<endl;
}
int main()
{
Base base;
Derived derive;
cout<<"&Base : "<<&base<<endl;//&Base : 0x7fffffffde88
cout<<"&Base : "<<(long*)&base<<endl;//&Base : 0x7fffffffde88
//第一个8字节为vptr指针即指向虚表的指针,将其解引用后为虚表的地址
//因为64位机器上 地址为8字节所以用long类型表示地址
printf("&Base虚表的地址 : %p\n",(long*)*(long*)&base);//&Base虚表的地址 : //0x555555557d08 虚表解引用后为第一个虚函数的地址
printf("&Base虚函数的地址 : %p\n",(long*)*(long*)*(long*)&base);//&Base虚函
//数的地址 : 0x5555555556aa
typedef void (*Function)();
//虚表解引用后为函数的地址
//此时需要创建函数指针来指向这个函数地址
Function pf=(Function)*(long*)*(long*)&base;
pf(); //hello
printf("&Base虚函数的地址 : %p\n",pf);//&Base虚函数的地址 : 0x5555555556aa
//可自行验证derived的虚函数
return 0;
}