C++多态虚函数纯虚函数demo

xiaoxiao2021-02-28  7

#include <iostream> using namespace std; class A //A是一个抽象类,不能new A直接实例化. { public: virtual void out1()=0; //纯虚函数:由子类实现 virtual ~A(){}; virtual void out2() //虚函数:默认实现 { cout<<"A(out2)"<<endl; } void out3() //普通函数:强制实现 { cout<<"A(out3)"<<endl; } }; class B:public A { public: //virtual ~B(){}; void out1()//纯虚函数:由子类实现 { cout<<"B(out1)"<<endl; } void out2()//虚函数:默认实现 { cout<<"B(out2)"<<endl; } void out3() { cout<<"B(out3)"<<endl; } }; int main() { /*多态:1.父类指针指向子类对象(不可倒过来.) 2.虚函数与纯虚函数确实调用子类的重写(覆盖)的函数,普通函数还是调用父类函数. */ A *ab = new B(); ab->out1();//子类实现父类的纯虚函数,此时调用子类out1() ab->out2();//子类重写(覆盖)父类的虚函数,此时调用子类out2() ab->out3();//父类是普通函数,没有多态功能. cout<<"************************"<<endl; B *bb = new B(); bb->out1(); bb->out2(); bb->out3(); cout<<"************************"<<endl; B cc; cc.out1(); cc.out2(); cc.out3(); cout<<"************************"<<endl; //A是一个抽象类,不能new A直接实例化.错误写法 /* A dd = new A; dd.out1(); dd.out2(); dd.out3(); */ delete ab; delete bb; return 0; }
转载请注明原文地址: https://www.6miu.com/read-2000028.html

最新回复(0)