#pragma once
#include<iostream>
namespace qcb{
class Base{
public:
virtual void func1()
{
std::cout << "Base::func1" << std::endl;
}
virtual void func2()
{
std::cout << "Base::func2" << std::endl;
}
private:
int a;
};
class Derive : public Base{
public:
virtual void func1()
{
std::cout << "Derive::func1" << std::endl;
}
virtual void func3()
{
std::cout << "Derive::func3" << std::endl;
}
virtual void func4()
{
std::cout << "Derive::func4" << std::endl;
}
private:
int b;
};
typedef void(*VFPTR)();
void PrintVTable(VFPTR vTable[])
{
所以每个元素都为一个指针,指向虚函数在代码段的相应位置
std::cout << "虚表地址>" << vTable << std::endl;
for (int i = 0; vTable[i] != nullptr; i++){
std::cout << "第" << i << "个虚函数地址: 0X" << vTable[i] << "->";
VFPTR f = vTable[i];
f();
}
std::cout << std::endl;
}
}
#include"polymorphism.h"
using namespace qcb;
int main()
{
Base b;
Derive d;
VFPTR* vTableb = (VFPTR*)(*(int*)&b);
PrintVTable(vTableb);
std::cout << std::endl;
VFPTR* vTabled = (VFPTR*)(*(int*)&d);
PrintVTable(vTabled);
return 0;
}
接下来做一些简单的总结,在C++继承中,每个类中如果有虚函数,那么该对象在生成时候,会有一张虚函数表(请区别虚基表的
|