• C++多态实现(虚函数,成员函数覆盖、隐藏)


    // 1.cpp : 定义控制台应用程序的入口点。
    //
    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    //#include <iostream.h>
    
    class animal
    {
    
    public:
    
        //
        void sleep()
        {
        cout<<"animal sleep"<<endl;
        }
    
        //
        void breathe()
        {
        cout<<"animal breathe"<<endl;
        }
    
        //
        virtual void eat()
        {
        cout<<"animal eat"<<endl;
        }
    
    };
    
    class fish:public animal
    
    {
    
    public:
    
        //隐藏基类animal::sleep(),而不是覆盖
        void sleep()
        {
         cout<<"fish sleep"<<endl;
        }
    
    
        //隐藏基类中animal::breathe(),而不是重载
        void breathe(int t)
        {
          if (t>0)
          {
            cout<<"t>0, fish breathe"<<endl;
          }
        }
    
        //覆盖基类中animal::eat()
        virtual void eat()
        {
        cout<<"fish eat"<<endl;
        }
    
    };
    
    void main()
    
        {
    
        fish fh;
        animal *pAn=&fh;
        fish *pFh=&fh;
    
        //1.基类和派生类,成员函数名称相同,参数不同,无论有无virtual关键字,基类函数均被隐藏(不是重载)
        pAn->breathe();//"animal breathe"
        //pFh->breathe();//error
        pFh->animal::breathe();//"animal breathe"
        pFh->breathe(1);//"t>0, fish breathe"
    
        //2.基类和派生类,成员函数名称相同,参数也相同,无virtual关键字,基类函数均被隐藏(不是覆盖)
        pAn->sleep();//"animal sleep"
        pFh->sleep();//"fish sleep"
    
        //3.虚函数(基类和派生类,成员函数名称相同,参数也相同,有virtual关键字),基类函数被覆盖
        pAn->eat();//"fish eat"
        pFh->eat();//"fish eat"
    
        }
  • 相关阅读:
    个人工作总结(2)
    个人工作总结(1)
    学习进度条
    学习进度条
    返回一个二维整数数组中最大联通子数组的和
    学习进度条
    构建之法阅读笔记02
    STM32F4寄存器初始化:PWM输出
    STM32F4跳转函数
    STM32F4寄存器串口DMA汇总
  • 原文地址:https://www.cnblogs.com/vranger/p/3163294.html
Copyright © 2020-2023  润新知