/** * @file vptr1.cpp * @brief C++虚函数vptr和vtable * 编译:g++ -g -o vptr vptr1.cpp -std=c++11 * @author 光城 * @version v1 * @date 2019-07-20 */ #include #include using namespace std; /** * @brief 函数指针 */ typedef void (*Fun)(); /** * @brief 基类 */ class Base { public: Base(){}; virtual void fun1() { cout << "Base::fun1()" << endl; } virtual void fun2() { cout << "Base::fun2()" << endl; } virtual void fun3(){} ~Base(){}; }; /** * @brief 派生类 */ class Derived: public Base { public: Derived(){}; void fun1() { cout << "Derived::fun1()" << endl; } void fun2() { cout << "DerivedClass::fun2()" << endl; } ~Derived(){}; }; /** * @brief 获取vptr地址与func地址,vptr指向的是一块内存,这块内存存放的是虚函数地址,这块内存就是我们所说的虚表 * * @param obj * @param offset * * @return */ Fun getAddr(void* obj,unsigned int offset) { cout<<"======================="<fun1(); cout<<"基类引用指向基类实例并调用虚函数"<