• C++虚函数与多继承


    虚函数

    C++用虚函数实现运行时多态,虚函数的实现是由两个部分组成的,虚函数指针与虚函数表。
    虚函数指针(vptr)是指向虚函数表的指针,在一个被实例化的对象中,它总是被存放在该对象的地址首位。而虚函数表(vtbl)用于保存类包含的虚函数指针列表:

    class Base {
    public:
        virtual void f() {
            std::cout << "Base::f()" << std::endl;
        }
    
    private:
        int n;
    };
    
    int main() {
        Base* base = new Base;
    
        return 0;
    }
    

    单继承下虚函数的内存布局

    在单继承中,子类覆盖父类的虚函数,其实只需要在子类对应的虚函数表中覆盖对应的虚函数指针即可:

    class Base {
    public:
        virtual void f() {
            std::cout << "Base::f()" << std::endl;
        }
    
    private:
        int n;
    };
    
    class Derived : public Base {
    public:
        void f() override {
            std::cout << "Derived::f()" << std::endl;
        }
    
        virtual void k() {
            std::cout << "Derived::k()" << std::endl;
        }
    
    private:
        int h;
    };
    
    int main() {
        Derived* derived= new Derived;
    
        return 0;
    }
    

    多继承下虚函数的内存布局

    class Base1 {
    public:
        virtual void f() {
            std::cout << "Base1::f()" << std::endl;
        }
    
    private:
        int n;
    };
    
    class Base2 {
    public:
        virtual void g() {
            std::cout << "Base2::g()" << std::endl;
        }
    
    private:
        int m;
    };
    
    class Derived : public Base1, public Base2 {
    public:
        void f() override {
            std::cout << "Derived::f()" << std::endl;
        }
    
        void g() override  {
            std::cout << "Derived::g()" << std::endl;
        }
    
        virtual void k() {
            std::cout << "Derived::k()" << std::endl;
        }
    
    private:
        int h;
    };
    
    int main() {
        Derived* derived= new Derived;
    
        return 0;
    }
    
  • 相关阅读:
    逆向技术汇总
    绕过安全软件设置注册表
    内存空间中的句柄,指针,对象,类
    COM组件的逆向
    组策略设置隔离文件夹
    VS2015驱动环境配置
    python批量提取eml附件
    反沙箱——SetErrorMode
    CrypMic分析报告
    反调试——jmp到那个地址
  • 原文地址:https://www.cnblogs.com/HachikoT/p/13747615.html
Copyright © 2020-2023  润新知