实验题目:
定义一个抽象基类shape,由它派生5个类:circle,square,rectangle,trapezoid,triangle.
用虚函数分别计算图形的面积,要求用基类指针数组,使他们的每个元素指向一个派生类对象 。
定义一个抽象基类shape,由它派生5个类:circle,square,rectangle,trapezoid,triangle.
用虚函数分别计算图形的面积,要求用基类指针数组,使他们的每个元素指向一个派生类对象 。
程序如下:
#include<iostream>
#include<math.h>
using namespace std;
class Shape
{
public:
virtual void ShapeName(){} //虚函数
virtual float area() { return 0.0; } //虚函数
};
class Circle:public Shape
{
public:
Circle(float r){ radius = r; }
virtual void ShapeName() { cout << "Circle area: "; } //对虚函数再定义
virtual float area() { return 3.14*radius*radius; }
protected:
float radius;
};
class Square :public Shape
{
public:
Square(float s){ side = s; };
virtual void ShapeName() { cout << "Square area: "; }
virtual float area(){ return side*side; }
protected:
float side;
};
class Rectangle :public Shape{
public:
Rectangle(float a, float b){ length = a; width = b; };
virtual void ShapeName() { cout << "Rectangle area: "; }
virtual float area(){ return length*width; }
protected:
float length;
float width;
};
class Trapezoid :public Shape{
public:
Trapezoid(float top, float bottom, float h){ topside = top; bottomside = bottom; high = h; };
virtual void ShapeName() { cout << "Trapezoid area: "; }
virtual float area(){ return (topside + bottomside)*high / 2; }
protected:
float topside;
float bottomside;
float high;
};
class Triangle :public Shape{
public:
Triangle(float a, float b, float c){ sidea = a; sideb = b; sidec = c; };
virtual void ShapeName() { cout << "Triangle area: "; }
virtual float area(){ float s = (sidea + sideb + sidec) / 2; float m = s*(s - sidea)*(s - sideb)*(s - sidec); return sqrt(m); }
protected:
float sidea;
float sideb;
float sidec;
};
int main(){
Circle circle(5);
Square square(5);
Rectangle rectangle(2, 3);
Trapezoid trapezoid(3, 4, 8);
Triangle triangle(3,4,5);
Shape *p[5] = { &circle, &square,&rectangle,&trapezoid,&triangle };
for (int i = 0; i < 5; i++){
p[i]->ShapeName();
cout << p[i]->area() << endl;
}
system("pause");
return 0;
}