c++多态性

来源:互联网 发布:37周胎儿发育标准数据 编辑:程序博客网 时间:2024/06/04 22:48

当一个基类的指针指向一个派生类的对象时,对于派生类中新派生出来的函数,此基类的指针是不能直接操作的,为了操作派生类中新派生出来的函数,需要在基类中加一个此函数的同名函数的接口;又为了省去加这个接口的麻烦,可使用dynamic_cast将基类类型的指针转换成派生类型的指针。

#include<iostream>#include<stdlib.h>using namespace std;class father{public:    virtual void smart(){ cout << "父亲很聪明" << endl; }    //virtual void beautiful(){}    //virtual ~father(){ cout << "析构父类" << endl; }};class son :public father{public:    void beautiful(){ cout << "儿子也很帅" << endl; }    //void smart(){ cout << "儿子很聪明" << endl; }    //~son(){ cout << "析构子类" << endl; }};void main(){    //father*p = new father;    //p->beautiful();    //p->smart();    //delete p;    //son a;    //a.beautiful();//对于父类中没有的对象,可在子类中直接派生成。    //a.smart();//子类也可以直接调用从父类继承来的函数    father*q = new son;//一个基类的指针指向子类的对象,为了可以直接访问基类的函数;对于子类的同名函数也想访问,加virtual;对于子类派生出的基类没有的函数,需要在基类中加一个虚函数接口。    q->smart();//虽然父类中的smart函数前面加了virtual,但若是子类中没有同名的smart函数,依然调用父类中的smart函数    son*ps = dynamic_cast<son*>(q);//将基类指针转换成派生类指针,转换成后只可访问派生类的函数,不可访问基类的函数    if (ps)        ps->beautiful();    else        cout << "父亲的指针" << endl;    //q->beautiful();    delete q;    father *t = new father;    son*pt = dynamic_cast<son*>(t);    if (pt)        pt->beautiful();    else        cout << "父亲的指针" << endl;    delete t;    son*w = new son;    w->beautiful();    w->smart();    delete w;    system("pause");}
0 0
原创粉丝点击