#include <iostream>
using std::cout;
using std::endl;
/* --------------------------------Base--------------------- */
class Base{
public:
virtual void print(){
cout<<"Base::print"<<endl;
}
virtual void display(){
cout<<"Base::display"<<endl;
}
virtual void show(){
cout<<"Base::show"<<endl;
}
private:
long _base=111;
};
/* ----------------------------------------------------- */
class Derived
:public Base
{
public:
virtual void display(){
cout<<"Derived::display"<<endl;
}
virtual void show(){
cout<<"Derived::show"<<endl;
}
private:
long _derived=478;
};
/* ----------------------------------------------------------------- */
void test(){
const char *p="hello";
printf("hello 地址 %p\n",p);
static int xwy=478;
cout<<"静态"<<endl<<&xwy<<endl<<endl;
Derived d;
long * pd=reinterpret_cast<long*>(&d);
cout<<std::hex<<std::showbase;
cout<<"Derived 对象 起始地址"<<endl<<*pd<<endl;
cout<<"Derived 对象 虚函数表的地址"<<endl<<pd[0]<<endl;
cout<<std::dec;
cout<<"Base _base 数据成员"<<endl<<pd[1]<<endl;
cout<<"Derived _derived 数据成员"<<endl<<pd[2]<<endl;
cout<<endl;
long *pvtable=reinterpret_cast<long*>(pd[0]);
cout<<std::hex<<std::showbase;
cout<<"Derived 虚函数表 虚函数print实现入口地址"<<endl<<pvtable[0]<<endl;
cout<<"Derived 虚函数表 虚函数display实现入口地址"<<endl<<pvtable[1]<<endl;
cout<<"Derived 虚函数表 虚函数show实现入口地址"<<endl<<pvtable[2]<<endl;
cout<<std::dec;
cout<<endl;
Base b;
cout<<"-----------------------------------"<<endl;
long *p1=(long* )(&b);
long *pb1=(long *)(*p1);
cout<<pb1<<endl;
long *pb=reinterpret_cast<long*>(&b);
cout<<std::hex<<std::showbase;
cout<<"Base 对象 虚函数表的地址 "<<endl<<pb[0]<<endl;
cout<<std::dec;
cout<<"Base 数据成员 _base "<<endl<<pb[1]<<endl<<endl;
long *pbtable=reinterpret_cast<long*>(pb[0]);
//print函数实现地址
//如果没有对基类的虚函数进行覆盖,那么虚函数表中的地址不会发生覆盖
cout<<std::hex<<std::showbase;
cout<<"Base 虚函数表 虚函数print实现入口地址"<<endl<<pbtable[0]<<endl;
cout<<"Base 虚函数表 虚函数display实现入口地址"<<endl<<pbtable[1]<<endl;
cout<<"Base 虚函数表 虚函数show实现入口地址"<<endl<<pbtable[2]<<endl;
cout<<std::dec;
cout<<endl;
typedef void (*Function)();
Function f=(Function)(pvtable[0]);
f();
f=(Function)(pvtable[1]);
f();
}
int main(void)
{
test();
return 0;
}
通过验证可以发现,如果虚函数表应该存放在文字常量区
- 已知如果虚函数表后定义,则应该存放在内存地址大于先定义的地方
- 先定义了一个文字常量区hello ,和静态区变量
- 后定义虚函数表,发现静态变量地址比后定义的虚函数表地址还要大,而虚函数表地址比文字常量区地址大,所以应该是存放在文字常量区