zoukankan      html  css  js  c++  java
  • C++多态性的理解

    本文章转载来自:http://www.sollyu.com/?p=627

    代码

    #include <iostream.h>
    class Animal
    {
    public:
     void eat()
     {
      cout<<"animal eat"<<endl;
     }
     void sleep()
     { 
      cout<<"animal sleep"<<endl;
     }
     void breathe()
     { 
      cout<<"animal breathe"<<endl;
     }
    };
    class Fish :  public Animal
    {
     void breathe()
     {
      cout<<"fish bubble"<<endl;
     }
    };
    void fn(Animal *pAn)
    {
     pAn->breathe();
    }
    void main()
    {
     Fish fh;
     Animal *pAn;
     pAn=&fh;
     fn(pAn);  
    }
    

    说明

    我们先来看看我们这个程序的运行结果:animal breathe 这里的结果是这样来理解的,因为fish是继承animal而来的,在内存区域中,fish的内存模型如下:

    C++多态性的理解

    故我们在将我们fish类的对象的指针传给我们的animal类的对象的指针的时候,我们系统执行的时候,系统调用的依然是我们积累里面的方法, 因为我们可以明显的发现我们的fish和animal的指针的首地址是一样的,故我们的运行时调用的就是我们的基类中的那个方法。

    我们再来看看我们的另外一个程序段代码:

    #include <iostream.h>
    class Animal
    {
    public:
        void eat()
        {
            cout<<"animal eat"<<endl;
        }
        void sleep()
        { 
            cout<<"animal sleep"<<endl;
        }
        virtual void breathe()
        { 
            cout<<"animal breathe"<<endl;
        }
    };
    class Fish :  public Animal
    {
        void breathe()
        {
            cout<<"fish bubble"<<endl;
        }
    };
    void fn(Animal *pAn)
    {
        pAn->breathe();
    }
    void main()
    {
        Fish fh;
        Animal *pAn;
        pAn=&fh;
        fn(pAn);   
    }
    

    程序的运行结果是:fish bubble 这里我们可以利用c++多态性来解释,我们加上virtual以后,这个基类中的方法变成了虚函数,系统在进行编译时,我们会先去调用我们基类中的方法,此时如果我们的子类中没有我们这个方法,我们还是会去调用我们基类中的方法。

    总结

    在利用我们的c++多态性的时候,我们这样来理解,当我们的基类中的方法为virtual时,我们的子类中有方法的我们会先去调用我们的子类中的相应的方法,如果我们的子类中没有的我们的系统才会去调用我们的父类的响应的方法。

    本篇文章由 爱推 发送

  • 相关阅读:
    机器人对话小程序
    partial关键字的含义
    TreeView控件常用写法
    电话本管理程序(实现增删改查功能)
    三层架构
    c# RegistryKey 的相关简单操作
    VS2010程序打包操作(超详细的)
    一些中文.net讲座
    对象表单自动数据邦定
    AspNetForums 2.0中的全文检索
  • 原文地址:https://www.cnblogs.com/sollyu/p/3869080.html
Copyright © 2011-2022 走看看