【Linux基础】虚函数

例 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)如果基类的成员函数是虚函数,在其派生类中,原型相同的函数自动成为虚函数。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值