C++虚函数
来源:互联网 发布:java后端需要学什么 编辑:程序博客网 时间:2024/04/28 08:40
参考
1. 如果不将某个函数定义为虚函数,在使用调用的是基类中的该方法
#include<iostream>using namespace std;class Shape{public: void draw(){ cout << "画图形"<<endl; }};class Rectangle :public Shape{public: void draw(){ cout << "画矩形"<<endl; }};class Round :public Shape{public: void draw(){ cout << "画圆形"<<endl; }};int main(){ Shape *shape; shape = new Rectangle(); shape->draw(); //画图形 (new Rectangle())->draw();//画矩形 system("pause"); return 0;}
2. 将draw方法定义为虚函数
class shape{public: shape(){ cout << "shape的构造函数" << endl; } virtual void draw(){ cout << "画图形" << endl; } ~shape(){ cout << "shape的析构函数" << endl; }};class rectangle :public shape{public: rectangle(){ cout << "rectangle的构造函数" << endl; } void draw(){ cout << "画矩形" << endl; } ~rectangle(){ cout << "shape的析构函数" << endl; }};class round :public shape{public: void draw(){ cout << "画圆形" << endl; }};int main(){ shape *shape; shape = new rectangle(); shape->draw(); //画矩形 (new rectangle())->draw();//画矩形 //system("pause"); return 0;}
3、在多态当中,一定要将基类的析构函数设置为虚函数,并将其实现。只有这样,才能够达到按对象构造的逆序来析构对象;否则析构的时候,只会析构基类的那一部分,派生类的那一部分无法析构
析构函数调用:先调用子类的析构函数,再调用父类的析构函数
构造函数调用:先调用父类的构造函数,再调用子类的构造函数
class Shape{public: Shape(){ cout << "shape construction" << endl; }; virtual void draw() = 0;//纯虚函数 virtual ~Shape(){ cout << "shape destruction" << endl; }};class Rectangle : public Shape{public: Rectangle(){ cout << "rectangle construction" << endl; }; void draw(){ cout << "rectangle draw" << endl; } ~Rectangle(){ cout << "rectangle destruction" << endl; }};class Round : public Shape{public: Round(){ cout << "round construction" << endl; }; void draw(){ cout << "round draw" << endl; } ~Round(){ cout << "round destruction" << endl; }};int main(){ Shape * s; s = new Rectangle(); s->draw(); delete s; s = new Round(); s->draw(); delete s; return 0;}
运行结果:
0 0
- C/C++--虚函数
- 【C/C++】纯虚函数
- C/C++, 虚函数表
- C++:虚函数用途
- 虚函数详解(C++)
- 虚函数(C++)
- c++-->虚函数 2
- C++ 虚函数
- C++:虚函数
- C++_虚函数
- 【c++】虚函数
- 【C++】虚函数
- C++ 虚函数
- [C++]虚函数
- 虚函数 假多态 C++
- C/C++ 虚函数
- C++:虚函数理解
- C++---虚函数
- [Leetcode,python] Reverse String 反转字符串
- Android之MVC设计模式
- 8.8 写一个函数,输入一个4位数字, 要求输出这4个数字字符, 但每两个数字间有一个空格。 如输入1990,应输出“1 9 9 0”。
- 【数据结构与算法学习笔记】PART1:算法分析(计算,计算模型,大O记号,算法分析,迭代与递归,动态控制)
- 天纵智能软件快速开发平台网格编辑插件
- C++虚函数
- Java-Collection集合总结
- 8张Linux思维导图(定位自己能力、清楚学习方向)
- ubuntu给手机建wifi
- Spring Security Reference 部分翻译
- Session的监听以及单点登录整合
- HDU 4183 最大流模板题
- DropdownList绑定的两种方法
- 培训总结集_(不更新)