定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea( )函数计算对象的面积,再使用Rectangle类创建一个派生类Square。在主函数中测试Rectangle、Circle和Square这三个类。将getArea()改造为虚函数。在主函数当中,只使用一个Shape *类型的指针p,依次指向Rectangle、Circle和Square的一个对象,并通过p->getArea()计算面积。
输入格式:
Rectangle的长和宽、Circle的半径、Square的边长
输出格式:
对应的面积,四舍五入到整数
输入样例 :
3 7 6 4
2.1 3.5 10.3 4.5
输出样例 :
21 113 16
7 333 20
#include <iostream>
#include<cmath>
using namespace std;
class Shape {
public:
virtual double getArea() { return 0; }//纯虚数函数
virtual ~Shape() {}//纯虚数构造函数
};
class Rectangle :public Shape {
private:
double len, wid;
public:
Rectangle(double l,double w):len(l),wid(w){}
double getArea() { return len * wid; }
};
class Circle :public Shape {
private:
double rou;
public:
Circle(double r):rou(r){}
double getArea() { return 3.14 * rou * rou; }
};
class Square :public Shape {
private:
double bi;
public:
Square(double b):bi(b){}
double getArea() { return bi * bi; }
};
int main()
{
double length, width, rough,bian;
while (cin >> length >> width >> rough >> bian) {
Shape* ps;
ps = new Rectangle(length, width);
Shape* pr;
pr = new Circle(rough);
Shape* pb;
pb = new Square(bian);
int a =round( ps->getArea());
int b = round(pr->getArea());
int c = round(pb->getArea());
cout << a << " " << b << " " <<c <<endl;
}
}
上篇文章末尾的问题就是我没有从Rectangle派生出Square