c++多态性

当一个基类的指针指向一个派生类的对象时,对于派生类中新派生出来的函数,此基类的指针是不能直接操作的,为了操作派生类中新派生出来的函数,需要在基类中加一个此函数的同名函数的接口;又为了省去加这个接口的麻烦,可使用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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值