本文主要是介绍C++多态虚函数demo(三十三),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码示例
#include<iostream>
#include<algorithm>
using namespace std;class Base{
public:void Fun(int x){cout<<"Base::Fun(int x)"<<endl;}void Fun(double x){cout<<"Base::Fun(double x)"<<endl;}//基类虚函数virtual void G(void){cout<<"Base::G(void)"<<endl;}
};class SubClass:public Base{
public:void Fun(int x){cout<<"SubClass::Fun(int x)"<<endl;}void Fun(double x){cout<<"SubClass::Fun(double x)"<<endl;}//覆盖基类虚函数virtual void G(void){cout<<"SubClass::G(void)"<<endl;}
};int main(){//SubClass *mm = new Base(); //错误//虚函数和纯虚函数的作用即多态,基类指针指向子类对象,当子类是G()重写(覆盖)了基类的虚函数,其实调用的是子类的G(),即多态精髓.Base *base = new SubClass();//基类指针指向子类对象//测试函数调用base->Fun(5);base->Fun(5.00);base->G();cout << "*********************" << endl;SubClass *cc = new SubClass();cc->Fun(5);cc->Fun(5.00);cc->G();cout << "*********************" << endl;Base *dd = new Base();dd->Fun(5);dd->Fun(5.00);dd->G();cout << "*********************" << endl;Base ee;ee.Fun(5);ee.Fun(5.00);ee.G();cout << "*********************" << endl;SubClass bb;bb.Fun(5);bb.Fun(5.00);bb.G();return 0;
}
这篇关于C++多态虚函数demo(三十三)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!