指向基类的指针,同名函数调用,引入虚函数。

来源:互联网 发布:linux下iscsi服务搭建 编辑:程序博客网 时间:2024/06/06 03:13
#include<iostream>using namespace std;class A{public:void fun(){cout<<"fun of A be called"<<endl;}};class B:public A{public:void fun(){cout<<"fun of B be called"<<endl;}};class C:public B{public:void fun(){cout<<"fun of C be called"<<endl;}};class D:public C{public:void fun(){cout<<"fun of D be called"<<endl;}};void f(A* ptr){ptr->fun();}int main(){A a;B b;C c;D d;a.fun();b.fun();c.fun();d.fun();A* p;p=&a;f(p);p=&b;f(p);p=&c;f(p);p=&d;f(p);}

声明A类下的void fun为 virtual void  fun则输出结果为



原创粉丝点击