利用虚函数机制编写计算正方形Square,圆Circle的面积(C++)
发布网友
发布时间:2022-05-10 18:37
我来回答
共1个回答
热心网友
时间:2023-10-22 05:31
#include <stdio.h>
#include <math.h>
#define PI 3.1415926
class Figure{
public:
Figure(double value);
virtual double area() = 0;
protected:
double r;
};
Figure::Figure(double value)
{
r=value;
}
class Square:public Figure{
public:
Square(double value):Figure(value){}
Square(const Square & s):Figure(s.r){}
double area();
};
class Circle:public Figure{
public:
Circle(double value):Figure(value){}
Circle(const Circle & c):Figure(c.r){}
double area();
};
double Square::area()
{
return r*r;
}
double Circle::area()
{
return PI*r*r;
}
void main()
{
Figure *pFigure;
int i;
Circle cls[5]={Circle(1.5),Circle(2.5),Circle(3.5),Circle(4.5),Circle(5.5)};
Square sqrs[5]={Square(1.5),Square(2.5),Square(3.5),Square(4.5),Square(5.5)};
pFigure=cls;
for (i=0;i<5;i++) {
printf("%f ",pFigure[i].area());
}
printf("\n");
pFigure=sqrs;
for (i=0;i<5;i++) {
printf("%f ",pFigure[i].area());
}
printf("\n");
}