当前位置:编程学习 > C/C++ >>

C++语言编程求助

 375041859@qq.com

13.图形面积的计算与存储

写一个程序,定义抽象基类Shape,由它派生出5个派生类:Circle(圆形)、Squre(正方形)、Rectangle(矩形)、Trapezoid(三角形)。用虚函数分别计算几种图形面积,并求它们的和。要求用基类指针数组,使它的每个元素指向一个派生类对象。要求将计算的各种图形面积以及它们和的结果存到磁盘文件ShapeArea.txt中。

答案:#include<iostream>
#include<fstream>
#include<string>
using namespace std;
#define PI 3.1415926
class shape
{
public:
 int length;
 shape(int length) { this->length =length; }//
 virtual double surface()=0;//
};
class circle:public shape  //圆
{
public:
 int radius;
public:
 circle (int radius) :shape(radius)
 {
  this->radius=radius;
 }
 double surface()
 {
  return (PI*radius*radius);
 }
};
class squre :public shape//正方形
{
public:
 int length;
public:
 squre(int length):shape(length)
 {
  this->length =length;
 }
 double surface()
 {
  return (length*length);
 }
};
class rectangle:public shape
{
public:
 int length;
 int width;
public:
 rectangle(int length,int width):shape(length)
 {
  this->length =length;
  this->width =width;
 }
 double surface()
 {
  return (length*width);
 }
};
class trapezoid:public shape
{
public:
 int length;
 int higth;
public:
 trapezoid(int length,int higth):shape(length)
 {
  this->length=length;
  this->higth=higth;
 }
 double surface()
 {
  return (0.5*length*higth);
 }
};
int main()
{
 shape * shapes[4];
 shapes[0]=new circle (5);
 double circles=shapes[0]->surface() ;
 shapes[1]=new squre (5);
 double squres=shapes[1]->surface ();
 shapes[2]=new rectangle (4,5);
 double rectangles=shapes[2]->surface ();
 shapes[3]=new trapezoid (4,5);
 double trapezoids=shapes[3]->surface ();
 string names[4]={"circle   ","squre    ","rectangle","trapezoid"};
 ofstream fout("ShapeArea.txt");
 for(int i=0;i<4;i++)
 {
  fout<<names[i]<<"   "<<shapes[i]->surface()<<endl;
 }
 fout<<"面积总和:"<<(circles+squres+rectangles+trapezoids)<<endl;
 return 0;
}

上一个:编程C++??
下一个:一个C++的编程.....

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,