多态性与虚函数
来源:互联网 发布:乐宝是什么软件 编辑:程序博客网 时间:2024/05/01 20:47
多态性:向不同的对象发送同一个消息,不同的对象在接受时会产生不同的行为(即方法)#include <iostream>using namespace std;class B{public: void print(){cout << "B::print()" << endl;} virtual void show();};void B::show(){cout << "B::show()" << endl;}class D :public B{public:void print(){cout << "B::print()" << endl;} void show(){cout << "D::show()" << endl;}};class E :public D{public:void show(){cout << "E::show()" << endl;}};void fun(B *pb){pb->show();}int main(){D d;B b;E e;fun(&d);fun(&b);fun(&e);getchar();return 0;}
最好把基类的析构函数声明为虚函数#include <iostream>using namespace std;class B{public: B(){cout << "B()" << endl;}virtual ~B(){cout << "~B()" << endl;}};class D :public B{public:D(){cout << "D()" << endl;}~D(){cout << "~D()" << endl;}};int main(){//D d;B *pb = new D;delete pb;getchar();return 0;}
本文出自 “顺势而为” 博客,转载请与作者联系!
0 0
- 多态性与虚函数
- 多态性与虚函数
- 多态性与虚函数
- 多态性与虚函数
- 多态性与虚函数
- 虚函数与多态性
- 多态性与虚函数
- 多态性与虚函数
- 虚函数与多态性
- 多态性与虚函数
- 多态性与虚函数
- 虚函数与多态性
- 多态性与虚函数
- 多态性与虚函数
- 虚函数与多态性
- 多态性与虚函数
- 多态性与虚函数
- C++多态性与虚函数
- “打擂台'找最大数
- 结构体内存对齐
- HDU2015
- 类和对象
- 二叉树的相关操作
- 多态性与虚函数
- Linux----find命令
- 回顾一些小函数
- Centos中vim的配置
- Linux中的ctags和Makefile使用
- c++:复数相加
- cef webui 足迹
- 100. Same Tree
- 【bzoj1146】【CTSC2008】【网络管理】【树链剖分+线段树套平衡树】