虚函数有个十分重要的作用,之动态绑定

来源:互联网 发布:蓝博软件 编辑:程序博客网 时间: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();
}

运行后结果如下:



从图中卡可以看出虚函数、非虚函数,虚函数覆盖机制的结果!

1 0
原创粉丝点击