谭浩强C++课后习题39——基类指针数组
题目描述:编写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle(圆形),Square(正方形),Rectangle(矩形),Trapezoid(梯形),Triangle(三角形)。用虚函数分别计算几种图形面积,并求他们的和。要求用基类指针数组,使它每一个元素指向一个派生类对象。
抽象基类:抽象基类题目类比
指针数组:是指存储指针的数组,每一个元素都是一个指针。
基类指针数组:每一个元素都是一个基类指针,用基类指针指向派生类对象可以调用派生类中重写的虚函数,从而实现多态性。
#include<iostream>
using namespace std;
//形状,抽象基类
class Shape {
public:
virtual double area()const = 0;
};
//圆类,继承形状类
class Circle:public Shape {
private:
double radius;
public:
Circle(double r) :radius(r) {}
virtual double area()const { return radius * radius * 3.14; }
};
//正方形类,继承形状类
class Square :public Shape {
private:
double length;
public:
Square(double l) :length(l) {}
virtual double area()const { return length * length; }
};
//长方形类,继承形状类
class Rectangle :public Shape {
private:
double length;
double heigth;
public:
Rectangle(double l, double h) :length(l), heigth(h) {}
virtual double area()const { return length * heigth; }
};
//梯形类,继承形状类
class Trapezoid :public Shape {
double top;
double bottom;
double height;
public:
Trapezoid(double t, double b, double h) :top(t), bottom(b), height(h) {}
virtual double area()const { return (top + bottom) * height * 0.5; }
};
//三角形类,继承形状类
class Triangle :public Shape {
double width;
double height;
public:
Triangle(double w, double h) :width(w), height(h) {}
virtual double area()const { return 0.5 * width * height; }
};
void printArea(Shape& s) {
cout << "面积为:" << s.area() << endl;
}
int main() {
Circle c(5);
cout << "圆形,";
printArea(c);
Square s(5);
cout << "正方形,";
printArea(s);
Rectangle r(4, 5);
cout << "矩形,";
printArea(r);
Trapezoid tr(1, 2, 3);
cout << "梯形:";
printArea(tr);
Triangle t(4, 3);
cout << "三角形,";
printArea(t);
Shape* pt[5] = { &c,&s,&r,&tr,&t };
double sumArea = 0;
for (int i = 0;i < 5;i++) {
sumArea += pt[i]->area();
}
cout << "总面积:" << sumArea << endl;
return 0;
}
运行测试结果: