您的位置:首页 > 编程语言 > C语言/C++

c++多态性

2016-06-29 20:11 211 查看
当一个基类的指针指向一个派生类的对象时,对于派生类中新派生出来的函数,此基类的指针是不能直接操作的,为了操作派生类中新派生出来的函数,需要在基类中加一个此函数的同名函数的接口;又为了省去加这个接口的麻烦,可使用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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: