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"); }
相关文章推荐
- 树莓派GPIO控制--C语言篇
- ubuntu系统vim基本配置
- C++错误累积
- #define a int[10] typedef int a[10]
- 大家好,这是我第一篇在CSDN上的博文,本篇主要讨论小型内存池的设计
- C++ 11 创建和使用 shared_ptr
- C++经典书籍推荐
- 《深入探索C++对象模型》第三章奇怪语句解释
- C++ 服务器端学习之心跳控制
- C++编程笔记:dll的生成与使用
- 解决 C/C++ 程序执行一闪而过的方法
- C++如何输出特定格式浮点数
- C++ explicit
- const在函数前与函数后的区别
- 矩阵取数游戏noip2006(c++ BigInteger的第一次运用)---重点!!
- C++中的异常处理(三)
- C++中的异常处理(二)
- C++中的异常处理(一)
- 快排算法及利用快排思想寻找第k大(小)的数
- C++ ------------排序算法(冒泡排序-快速排序-选择排序-插入排序-希尔排序)