您的位置:首页 > 其它

7.30定义一个公共基类Shape,实现运行时的多态性

2014-08-29 18:46 549 查看
定义一个公共基类Shape,它表示一个封闭平面几何图形。

然后,从Shape类派生出三角形类Triangle、矩形类Rectangle和圆类Circle,

在基类中定义纯虚函数show和area,分别用于显示图形信息和求相应图形的面积,

并在派生类中根据不同的图形实现相应的函数。要求实现运行时的多态性。

#include <cmath>

#include<iostream>

using namespace std;

const double PI = 3.1415926535;

class Shape

{ public:
virtual  void show( ) = 0;
virtual  double area( ) = 0;

 };

class Rectangle: public Shape

{public:

Rectangle( ){length = 0; width = 0; } 

Rectangle(double len, double wid){ length = len; width = wid; }

double area( ){return length*width;} 

void show( )

{ cout << "length = " << length << '\t' << "width = " << width << endl; } 

private:

double length, width; 

};

class Triangle: public Shape

{public:
Triangle( ){a = 0; b = 0; c = 0;}
Triangle(double x, double y, double z){a = x; b = y; c = z;}
double area( )

{  double s = (a+b+c)/2.0;

   return sqrt(s*(s - a)*(s - b)*(s - c));

}
void show( )

{cout << "a = " << a << '\t' << "b = " << b << '\t' << "c = " << c << endl;}

private:

double a, b, c; 

};

class Circle: public Shape

{public:

Circle( ){radius = 0; }

Circle(double r){radius = r;}

double area( ){return PI*radius*radius;} 

void show( ){cout << "radius =" << radius << endl;}

private:

double radius;

};

int main( )

{    Shape *s = NULL;
Circle c(10);
Rectangle r(6, 8);
Triangle t(3, 4, 5);
c. show( );
cout << "圆面积:" << c.area( ) << endl;
s = &r;
s -> show( );
cout << "矩形面积:" << s -> area( ) << endl;
s = &t;
s -> show( );
cout << "三角形面积:" << s -> area( ) << endl;
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐