声明抽象基类Shape,由它派生出3个子类:Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别求出以上三者的面积,三个图形的数据在定义对象时给定。再设计一个函数sumArea,求出三个图形面积之和。要求用基类指针数组,使它的每一个元素指向一个派生类对象。
View Code
#include <iostream> #include <cmath> using namespace std; const double PI = acos(-1.0); class Shape { public: virtual double getArea() = 0; }; class Circle : public Shape { private: double R; public: Circle(double r = 0) : R(r) {}; double getArea() { return PI * R * R; } }; class Rectangle : public Shape { private: double len,high; public: Rectangle(double l = 0, double h = 0) : len(l), high(h) {}; double getArea() { return len * high; } }; class Triangle : public Shape { private: double di,H; public: Triangle(double l = 0, double h = 0) : di(l), H(h) {}; double getArea() { return di * H / 2; } }; template <class T> void printArea(T sa) { cout << sa.getArea() << endl; } double sumArea(Shape** p,int x) { double sum = 0; for(int i = 0;i < x; i++) { sum += p[i]->getArea(); } return sum; } int main() { Circle circle(12.6); Rectangle rectangle(4.5,8.4); Triangle triangle(4.5,8.4); cout<<"area of circle ="; printArea(circle); cout<<"area of rectangle ="; printArea(rectangle); cout<<"area of triangle ="; printArea(triangle); Shape *pt[3] = {&circle,&rectangle,&triangle}; cout << sumArea(pt,3) << endl; return 0; }