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"
    
        }
  • 相关阅读:
    Swift入门篇-Hello World
    Swift入门篇-swift简介
    Minecraft 插件 world edit 的cs 命令
    搭建本地MAVEN NEXUS 服务
    MC java 远程调试 plugin 开发
    企业内部从零开始安装docker hadoop 提纲
    javascript 命令方式 测试例子
    ca des key crt scr
    JSF 抽象和实现例子 (函数和属性)
    form 上传 html 代码
  • 原文地址:https://www.cnblogs.com/vranger/p/3163294.html
Copyright © 2011-2022 走看看