您的位置:首页 > 其它

虚函数(virtual)与多态(polymorphism)、动态绑定(dynamic binding)

2009-04-27 12:16 295 查看
虚函数(virtual)与多态(polymorphism)、动态绑定(dynamic binding

首先介绍虚函数、多态、动态绑定的的概念:
1.虚函数产生意义:就是“违反”“如果你以一个基类指针指向一个派生类的对象,那么通过该指针你就只能够调用基类所定义的成员函数”这条规定而诞生的。简言之,就是在派生类的成员函数前面加“virtual“关键字就变成了虚函数。基类指针就可以调用这个虚函数。
2.多态意义:就是让处理“基类的对象”的程序代码能够完全无碍地继续适应处理“派生类对象”。多态的本质是同样的用法在实现上却是不同的。
举一个绘图形例子:
#include <iostream.h>
class Shape//形状
{
public:
virtual void DrawSelf()
{
cout << " Shape:我是一个什么也绘不出的图形" << endl;
}
};
class Polygo:public Shape//多边形
{
public:
void DrawSelf()
{
cout << " Polygo:连接各顶点" << endl;
}
};
class Circ:public Shape//圆
{
public:
void DrawSelf()
{
cout << " Circ:以圆心和半径为依据画弧" << endl;
}
};
int main()
{ Shape *pShape;//基类指针
Polygo polygon; //派生类对象
Circ circ;
pShape = & polygon;//基类指针指向派生类
pShape ->DrawSelf();//程序代码一样但实现的结果不一样,这就满足多态的特征。
pShape = & circ;
pShape ->DrawSelf();
return 0;
}
输出结果:
Polygo:连接各顶点
Circ:以圆心和半径为依据画弧

3.虚函数都是动态绑定。每个“含有虚函数的类”,C++编译器都会给它做一个虚函数表。表中每一个元素都指向一个虚函数地址。
上例子衍生:
#include <iostream.h>
class Shape//形状
{
public:
virtual void DrawSelf(){};
int a;
}
class Polygo:public Shape//多边形
{
public:
virtual void DrawSelf(){};
virtual void SetColor(){};
int n;
int color;
};
class Circ:public Shape//圆
{
public:
void DrawSelf(){} ;
virtual void SetPoint(){};
int r;
int x,y;
};
int main()
{ cout<<sizeof(Shape)<<endl;
cout<<sizeof(Polygo)<<endl;
cout<<sizeof(Circ)<<endl;
Shape shape;//基类对象
Polygo polygo; //派生类对象
Circ circ;

polygo.n =6;
polygo.color = 250;
circ.r = 20;
circ.x = 10;
circ.y = 10;
cout<<polygo.n<<endl;
cout<<polygo.color<<endl;
cout<<circ.r<<endl;
cout<<circ.x<<endl;
cout<<circ.y<<endl;
cout<<&polygo<<endl;
cout<<&(polygo.n)<<endl;
cout<<&(polygo.color)<<endl;

cout<<&circ<<endl;
cout<<&(circ.r)<<endl;
cout<<&(circ.x)<<endl;
cout<<&(circ.y)<<endl;
return 0;
}
输出结果:
8
16
20
1
6
250
20
10
10
0x0013ff78
0x0013ff7c
0x0013ff68
0x0013ff6c
0x0013ff70
0x0013ff74
0x0013ff54
0x0013ff5c
0x0013ff60
0x0013ff64

Shape、 Polygo 、Circ内存结构:

Shape
0x0013ff78 vptr
0x0013ff7c a
---->
(*DrawSelf())
---->class Shape:DrawSelf()

Polygo
0x0013ff68 vptr
0x0013ff6c a
0x0013ff70 n
0x0013ff74 color
--à
(*DrawSelf())
(*SetColor())
---->class Polygo:DrawSelf()
---->class Polugo: SetColor()

Circ
0x0013ff54 vptr
0x0013ff58 a
0x0013ff5c r
0x0013ff60 x
0x0013ff64 y
--à
(*DrawSelf())
(*SetPoint())
---->class Circ:DrawSelf()
---->class Circ: SetPoint()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: