虚函数有个十分重要的作用,之动态绑定
来源:互联网 发布:蓝博软件 编辑:程序博客网 时间:2024/06/05 09:08
将基类指针指向派生类,可调用派生类声明的虚函数;所以在事件运行中可根据动态传递过来的形参,完成虚函数的动态绑定!
如果调用非虚函数,则无论实际对象是什么类型,都执行基类类型所定义的函数;如果调用虚函数,则直到运行时才能确定到底调用哪个函数,运行的虚函数是 引用所绑定的 或 指针所指向的 所属类型定义的 版本
这也是C++多态性的体现!
#include "stdio.h"
#include <Winsock2.h>
#pragma comment(lib, "WS2_32")
char str[20]={0};
class pubclass
{
public:
virtual void pubout();
void fun()
{
printf("base xu\n");
}
};
void pubclass::pubout()
{
printf("form pubclass pubout\n");
}
class testclass:public pubclass
{
public:
int pub_datain;
int pub_dataout;
//protected:
//private:
void appendin(int in,int out);
void pubout();
void fun()
{
printf("child xu\n");
}
};
void testclass::appendin(int in,int out)
{
printf("in is %hu\n",in);
printf("out is %d\n",out);
}
void testclass::pubout()
{
printf("form testclass pubout\n");
}
#define test(page, category, property) \
if (int prop = property) \
{ \
page->appendin(category, prop); \
}
void main()
{
int i=1;
testclass *ctest;//派生类
testclass cctest;
pubclass pclass;//基类
pubclass *ppclass;//基类指针
test(ctest,51,2);
if (int prop = 0)
{
printf("ok\n");
}else{
printf("error\n");
}
i=gethostname(str, 20);
printf("%d\n",i);//=-1,返回错误
//printf("%s\n",*(&str[0]));
printf("ppclass指向基类;\n");
ppclass=&pclass;//基类
ppclass->pubout();//指向虚函数
ppclass->fun();//非虚函数,始终调用基类函数
printf("ppclass指向派生类;\n");
ppclass=&cctest;//派生类
ppclass->pubout();//指向虚函数,调用派生类的函数
ppclass->pubclass::pubout();//覆盖虚函数机制,调用了基类的函数
ppclass->fun();//非虚函数
getchar();
}
运行后结果如下:
从图中卡可以看出虚函数、非虚函数,虚函数覆盖机制的结果!
- 虚函数有个十分重要的作用,之动态绑定
- 虚函数的动态绑定
- 虚函数的动态绑定
- C++ 对比虚函数的动态绑定
- 虚函数的静态绑定和动态绑定
- 静态绑定、动态绑定、虚函数的工作原理
- html之动态绑定带参数的函数
- c++静态绑定和动态绑定以及虚函数中缺省参数的绑定
- 虚函数与动态绑定
- 虚函数与动态绑定
- C++虚函数动态绑定
- php是十分重要的
- 触发动态绑定的2个条件
- 虚函数与动态绑定的那点事
- C++ 虚函数的深入思考 -动态绑定案例
- C++中虚函数动态绑定的实现
- 多态、虚函数、动态绑定的关系
- javascript动态绑定带参数的函数
- java Io File类 笔记
- DAY1:leetcode #1 Two Sum
- Cannot modify header information – headers already sent by cookie 的解决办法
- ios学习--layer的应用(设置UIView子类边框属性&字体阴影属性)
- Go语言学习九:接口、错误处理
- 虚函数有个十分重要的作用,之动态绑定
- odoo8登录时,同帐号在其它客户端的连接自动退出
- Titanic: Machine Learning from Disaster——Logistic regression
- java Io reader writer 笔记3
- HDU 5112 A Curious Matt(水~)
- BZOJ 1486: [HNOI2009]最小圈
- 解决 gradlew 构建错误: 编码 GBK的不可映射字符
- 6.2.4 随机游走(Random Walk)
- Openstack 源码修改,实现nova boot 创建的虚拟机支持USB 重定向