例 6 用虚函数实现动态多态
#include <iostream.h>
#include <string.h>
class CPoint
{
private:
int X;
int Y;
public:
CPoint(int x=0, int y=0)
{
X=x;
Y=y;
}
CPoint(CPoint &p)
{
X=p.X;
Y=p.Y;
}
int GetX()
{
return X;
}
int GetY()
{
return Y;
}
};
class CShape
{
private:
char Color[10];
public:
CShape(char *c)
{
strcpy(Color,c);
}
virtual void Draw()
{
cout << "Draw a Shape. The color is " << Color << endl;
}
void PrintColor()
{
cout << Color << endl;
}
};
class CLine:public CShape
{
private:
CPoint Start;
CPoint End;
public:
CLine(CPoint s, CPoint e, char *c):CShape(c),Start(s),End(e)
{}
virtual void Draw()
{
cout << "Draw a Line from (" << Start.GetX() << "," << Start.GetY();
cout << ") to ("<< End.GetX() << "," << End.GetY() << "), with color ";
PrintColor();
}
};
class CCircle:public CShape
{
private:
CPoint Center;
int Radius;
public:
CCircle(CPoint ctr, int r, char *c):CShape(c),Center(ctr)
{
Radius = r;
}
virtual void Draw()
{
cout << "Draw a Circle at center (" << Center.GetX() << "," ;
cout << Center.GetY()<< ") with radius " << Radius << " and color ";
PrintColor();
}
};
void main()
{
CShape *ps[3];
CShape s("Red");
CPoint p1(10,10), p2(100,100),p3(50,50);
CLine l(p1,p2,"Green");
CCircle c(p3, 20, "Black");
ps[0] = &s;
ps[1] = &l;
ps[2] = &c;
for(int i=0; i<3; i++)
ps->Draw();
}
程序运行结果为:
Draw a Shape. The color is Red
Draw a Line from (10, 10) to (100, 100) , with color Green
Draw a Circle at center (50, 50) with radius 20 and color Black
总结:
(1)将成员函数声明为虚函数,在函数原型前加关键字virtual,如果成员函数的定义直接写在类中,也在前面加关键字virtual。
(2)将成员函数声明为虚函数后,再将基类指针指向派生类对象,在程序运行时,就会根据指针指向的具体对象来调用各自的虚函数,称之为动态多态。
(3)如果基类的成员函数是虚函数,在其派生类中,原型相同的函数自动成为虚函数。
本文转载于唯C教育,【Linux基础】虚函数
http://www.weicedu.com/forum.php?mod=viewthread&tid=79&fromuid=4
(出处: http://www.weicedu.com/)
http://www.weicedu.com/forum.php?mod=viewthread&tid=79&fromuid=4
(出处: http://www.weicedu.com/)