//利用基类,派生类,虚函数,来进行对象多态性的演示。
#include<iostream>//基类为两个数据,两个派生类分别为三角形,矩形。
using namespace std;
class figure
{
protected:
double x,y;//因为要进行派生,所以定义为保护型。
public:
void setdata(double a,double b)
{
x=a,y=b;
}
virtual void showarea(void)//基类中定义虚函数。关键字virtual
{
cout<<"no area computation defined for this clss!!!"<<endl;
}
};
class triangle:public figure
{
public:
void showarea(void)
{
cout<<"triangle with high="<<x<<" and with wide="<<y<<endl;
cout<<"has an area :"<<0.5*x*y<<endl;
}
};
class rectangle:public figure
{
public:
void showarea(void)
{
cout<<"rectangle with high="<<x<<" and with wide="<<y<<endl;
cout<<"has an area :"<<x*y<<endl;
}
};
int main()
{
triangle a;
rectangle b;
figure c;
c.setdata(2.3,5.6);
a.setdata(2.3,5.6);
b.setdata(2.3,5.6);
c.showarea();
a.showarea();
b.showarea();
return 0;
}
利用基类,派生类,虚函数,来进行对象多态性的演示
最新推荐文章于 2023-04-25 14:56:58 发布