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
- C++:多态性
- C++-多态性
- C++---多态性
- C+++多态性
- 【C#】多态性
- C++---------【多态性】之【静态多态性】
- 多态性C++[转]
- 多态性C++[转]
- C++:多态性 (三)
- c/c++中的多态性
- 【C#】C#多态性
- C++_多态性
- 5.2什么是多态性【C++】
- C#教程第九课:多态性
- C#教程 第九课:多态性
- C plus plus 的多态性
- C#教程第九课:多态性
- Objective-C第六讲-多态性
- 获取input标签后的文本及<input />,<input>和<input></input>区别
- 图像轮廓提取关键函数
- Android Studio插件整理
- SpringMVC入门-第一节:简介
- 远程库的使用
- c++多态性
- 技术至上
- Android 6.0编译问题
- 树莓派GPIO控制--python篇
- std::function用法
- 设计模式-模板方法模式
- 获得打气筒的三种方式,以及ListView的使用与优化
- c++多重继承
- android Sensor相关工作