C++中的虚函数详解
来源:互联网 发布:守护进程 windows 编辑:程序博客网 时间:2024/06/11 19:57
#**C++中虚函数的使用****
虚函数一般使用在C++的多态性(多态的共有继承相关)**
多态性:1.可以在派生类中重新定义基类的方法
2.使用虚方法比如下面一个小代码:
比如,一个酒店的用户:分为普通人,和VIP用户。
普通人和vip用户都必须登记个人信息,都有consume的方法而普通用户没有折扣,而vip有折扣并且vip也有礼物送,普通用户没有
下面的就是code:
man.h
#include<string>#include<iostream> //必须要声明,否则string类型无法读出,哭了这using namespace std;class averageman{private:string S_name; //姓名int I_years; //年龄 bool sex; //性别,true代表男,false代表女public:averageman(string S = "nullbody", int ye = 0, bool se = 0);//开始给形参赋初值void print();virtual void consume(); //消费为虚函数virtual ~averageman() {} //虚析构函数};class vipman:public averageman{private:int discount;public:vipman(averageman &b, int dis);virtual void consume(); //虚函数void present();~vipman() {}};man.cpp
#include "man.h"#include<iostream>using namespace std;averageman::averageman(string S, int ye, bool se){S_name = S;I_years = ye;sex = se;}void averageman::print(){cout << "name:" << S_name << endl;cout << "years:" << I_years << endl;if (sex)cout << "sex:male" << endl;else cout << "sex:female" << endl;}void averageman::consume(){cout << "you are the ordinary customer,can't have a discount" << endl;}vipman::vipman(averageman &b, int dis) :averageman(b){discount = dis;}void vipman::consume(){cout << "you are the vip customer,you can have a "<<discount<<"% discount"<<endl;}main.cpp
#include "man.h"#include <iostream>using namespace std;int main(){averageman A("Mary", 18, false);averageman B("Tom", 20, true);vipman C(B, 88);averageman *a1 = &A;averageman *b1 = &C;a1->print();b1->print();a1->consume();b1->consume(); //你会注意到,你并不能调用present这个函数!system("pause");}在函数代码中,我定义了两个基类指针a1,b1;
a1引用的是基类,b1引用的是派生类
当它们同时调用consume函数时,如果consume是虚函数,则,调用引用的对象的consume函数
故 a1调用基类的函数,b1调用派生类的函数
如果consume不是虚函数,则,都调用基类的consume函数
即a1和b1调用基类的consume函数!
0 0
- C中的printf函数详解
- 虚函数详解(C++)
- C语言中的system函数参数详解
- C 中的main函数的参数详解
- 详解C标准库中的atexit()函数
- C/C++中的freopen()函数使用详解
- 详解C语言中的fopen()函数和fdopen()函数
- C#(C Sharp)中的时间日期函数详解
- C中的malloc()函数和free()函数与C++中的new()函数和delete()函数详解
- C++中的虚函数详解
- C++中的虚函数详解
- c++中的虚函数详解
- [C++]C++中的虚函数
- C语言中的printf族函数深入详解
- C编程中的malloc()和free()函数使用详解
- C语言中的快速排序 qsort函数详解
- Python中的函数详解
- c#日期函数详解
- 使用FileUtils简化你的文件操作
- 个人的vim配置
- hdu1532-Drainage Ditches
- R语言-数据处理包 dplyr
- NDK工具使用,JNI开发
- C++中的虚函数详解
- IOS开发中WebView加载资源路径问题
- RxBus事件总线的实现
- Ng机器学习 Week8 Unsupervised Learning
- python opencv3 安装
- HBase 0.98 分布式集群安装详解
- 判断合法标识符
- ssh框架
- 鉴别图像中含有给定颜色的所有像素