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" }
知识就是力量!