声明抽象基类 Shape,由它派生出3个派生类: Circle(圆形)、 Rectangle(矩形)、 Triangle(三角形),用一个函数 printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
1.程序代码:
#include <iostream>
#include <iomanip>
using namespace std;
class Shape
{
public:
virtual double area() = 0; //定义一个纯虚函数
};
void printArea(Shape& shape)
{
cout << shape.area() << endl;
}
class Circle :public Shape
{
public:
Circle(double a) :r(a) {}
virtual double area()
{
return (3.14159 * r * r);
}
protected:
double r;
};
class Rectangle :public Shape
{
public:
Rectangle(double x, double y) :a(x), b(y) {}
virtual double area()
{
return (a * b);
}
protected:
double a;
double b;
};
class Triangle :public Shape
{
public:
Triangle(double x, double y) :w(x), h(y) {}
virtual double area()
{
return (w * h / 2);
}
protected:
double w;
double h;
};
int main()
{
Circle cir1(3);
cout << "area of circle = ";
printArea(cir1);
Rectangle rec1(3, 4);
cout << "area of rectangle = ";
printArea(rec1);
Triangle tri1(4, 5);
cout << "area of triangle = ";
printArea(tri1);
return 0;
}
2.运行结果: