zoukankan      html  css  js  c++  java
  • C++中类的多态与虚函数的使用

         多态的这个概念稍微有点模糊,如果想在一开始就想用清晰用语言描述它,让读者能够明白,似乎不太现实,所以我们先看如下代码:

    //例程1 
    #include <iostream>     
    using namespace std;   
       
    class Vehicle 
    {   
    public:   
        Vehicle(float speed,int total) 
        { 
            Vehicle::speed=speed; 
            Vehicle::total=total; 
        } 
        void ShowMember() 
        { 
            cout<<speed<<"|"<<total<<endl; 
        } 
    protected:   
        float speed; 
        int total; 
    };   
    class Car:public Vehicle   
    {   
    public:   
        Car(int aird,float speed,int total):Vehicle(speed,total)   
        {   
            Car::aird=aird;   
        } 
        void ShowMember() 
        { 
            cout<<speed<<"|"<<total<<"|"<<aird<<endl; 
        } 
    protected:   
        int aird; 
    };   
     
    void main()   
    {   
        Vehicle a(120,4); 
        a.ShowMember(); 
        Car b(180,110,4); 
        b.ShowMember(); 
        cin.get(); 
    }

      在c++中是允许派生类重载基类成员函数的,对于类的重载来说,明确的,不同类的对象,调用其类的成员函数的时候,系统是知道如何找到其类的同名成员,上面代码中的a.ShowMember();,即调用的是Vehicle::ShowMember(),b.ShowMember();,即调用的是Car::ShowMemeber();。

      但是在实际工作中,很可能会碰到对象所属类不清的情况,下面我们来看一下派生类成员作为函数参数传递的例子,代码如下:

    //例程2 
    #include <iostream>     
    using namespace std;   
       
    class Vehicle 
    {   
    public:   
        Vehicle(float speed,int total) 
        { 
            Vehicle::speed=speed; 
            Vehicle::total=total; 
        } 
        void ShowMember() 
        { 
            cout<<speed<<"|"<<total<<endl; 
        } 
    protected:   
        float speed; 
        int total; 
    };   
    class Car:public Vehicle   
    {   
    public:   
        Car(int aird,float speed,int total):Vehicle(speed,total)   
        {   
            Car::aird=aird;   
        } 
        void ShowMember() 
        { 
            cout<<speed<<"|"<<total<<"|"<<aird<<endl; 
        } 
    protected:   
        int aird; 
    };   
     
    void test(Vehicle &temp) 

        temp.ShowMember(); 

     
    void main()   

        Vehicle a(120,4); 
        Car b(180,110,4); 
        test(a); 
        test(b); 
        cin.get(); 
    }

  • 相关阅读:
    文件上传利用总结
    通过WebGoat学习java反序列化漏洞
    C# Bat批处理文件创建、执行
    C# 删除目录下所有文件
    是时候做一点属于自己的东西了
    2021.09.26省市县三级联动最新数据库,附脚本
    SpringBoot 整合Easy Poi 下载Excel(标题带批注)、导出Excel(带图片)、导入Excel(校验参数,批注导出),附案例源码
    NeRF 核心思想简记
    R-CNN系列核心思想简单记录
    HeapDump性能社区Young GC异常问题排查实战案例精选合集
  • 原文地址:https://www.cnblogs.com/zhen/p/1503029.html
Copyright © 2011-2022 走看看