zoukankan      html  css  js  c++  java
  • 016 虚函数

    /*
    目录:
        一 概念
        二 简单对比
       三 简单对比 - 图形
    */

    一 概念

    /*
    
    // 虚函数    
        虚函数一定是重写函数,在基类重写函数前加virtual
        
        使用:
            1 类对象: 使用什么对象调用对应类的重写函数
            2 基类指针: 
                (1) 调用普通函数: 对应类函数 
                (2) 调用virtual函数: 指针指向的类
        
        原理: 
            1 对象首部多个指针,指针指向虚表        
            
        思想:
            抽象与实现
                基类: 概念、抽象
                派生类: 具体对象
            
            静态绑定和动态绑定
                静态: 编译时绑定,通过对象调用(对象类型)
                动态: 运行时绑定,通过地址调用(根据虚表)
                
    // 纯虚函数: 
            1 不能定义基类对象
            2 派生类必须有重写函数
            3 含纯虚函数的基类,叫做抽象类。纯虚函数也称为抽象函数。
    */

    二 简单对比

    #pragma once
    #include <iostream>
    
    using namespace std;
    
    class CBase
    {
    public:
        void RealFunc()
        {
            cout << "CBase::RealFunc()" << endl;
            m_i = 0x10;
        }
        virtual void VirtualFunc()
        {
            cout << "CBase::VirtualFunc()" << endl;
            m_i = 0x11;
        }
    
        int m_i;
    };
    
    
    class CDerived :public CBase
    {
    public:
        void RealFunc()
        {
            cout << "CDerived::RealFunc()" << endl;
            m_j = 0x20;
        }
        void VirtualFunc()
        {
            cout << "CDerived::VirtualFunc()" << endl;
            m_j = 0x22;
        }
    
    private:
        int m_j = 0x88;
    };
    
    
    int main()
    {
        CBase b;
        b.RealFunc();
        b.VirtualFunc();
        cout << sizeof(b) << endl;
    
        CDerived d;
        d.RealFunc();
        d.VirtualFunc();
        cout << sizeof(d) << endl;
    
        CBase *pb;
        pb = &b;
        pb->RealFunc();
        pb->VirtualFunc();
    
        pb = &d;
        pb->RealFunc();
        pb->VirtualFunc();
    
    
        return 0;
    }

    三 简单对比 - 图形

      压缩包: 链接

  • 相关阅读:
    7.2对象的生命周期
    7.2.2垃圾收集和对象的终结
    7.1.2验证
    发现电脑上装着liteide,就用golang做一个TCP通讯测试(支持先启动client端和断线重连)
    C++读写局域网共享
    C++编写 动态链接库dll 和 调用dll
    VBA果然很强大
    [Windows]查看运行进程的参数【wmic】
    自旋锁-SpinLock(.NET 4.0+)
    C#并行和多线程编程
  • 原文地址:https://www.cnblogs.com/huafan/p/11980699.html
Copyright © 2011-2022 走看看