/*已定以一个shape抽象类,在此基础上派生出矩形rectangle和圆形circle,
二者都有getarea()函数计算对象的面积,并编写测试的main函数*/
#include<iostream>
#define p 3.1415926
using namespace std;
class shape
{
public:
virtual double getarea()=0;
};
class rectangle:public shape
{protected:
double lenght,width;
public:
rectangle(double l=0,double w=0)
{
lenght=l;width=w;
}
double getarea()
{
return lenght*width;
}
};
class circle:public shape
{
protected:
double ra;
public:
circle(double r=0){ra=r;}
double getarea()
{
return p*ra*ra;
}
};
void fun(shape *prt)
{
cout<< prt->getarea()<<endl;
}
void main()
{//必须建立基类对象,并且通过基类对象指针来访问派生的函数
shape *pt;
rectangle t(3.2,4.5);
circle j(2);
cout<<"rectangle area:";
pt=&t;
fun(pt);
cout<<"cricle area:";
pt=&j;
fun(pt);
cout<<endl;
}
二者都有getarea()函数计算对象的面积,并编写测试的main函数*/
#include<iostream>
#define p 3.1415926
using namespace std;
class shape
{
public:
virtual double getarea()=0;
};
class rectangle:public shape
{protected:
double lenght,width;
public:
rectangle(double l=0,double w=0)
{
lenght=l;width=w;
}
double getarea()
{
return lenght*width;
}
};
class circle:public shape
{
protected:
double ra;
public:
circle(double r=0){ra=r;}
double getarea()
{
return p*ra*ra;
}
};
void fun(shape *prt)
{
cout<< prt->getarea()<<endl;
}
void main()
{//必须建立基类对象,并且通过基类对象指针来访问派生的函数
shape *pt;
rectangle t(3.2,4.5);
circle j(2);
cout<<"rectangle area:";
pt=&t;
fun(pt);
cout<<"cricle area:";
pt=&j;
fun(pt);
cout<<endl;
}