zoukankan      html  css  js  c++  java
  • 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"
    
        }
  • 相关阅读:
    APP 打包成功的四种方法 转自
    设置启动页
    大数据之医疗行业数据分析
    实验三(FCFS ,SJF,HRRN)
    实验四 用信号量解决进程互斥与同步问题
    实验二 (3)最短作业优先调度
    实验二 (2)优先数调度
    实验二 (1)先来先服务进程调度
    实验一
    Hdoj 1253
  • 原文地址:https://www.cnblogs.com/vranger/p/3163294.html
Copyright © 2011-2022 走看看