谁能帮我解说一下以下这个C++程序吗?下列 shape 类是一个表示形状的抽象类, area() 为求图形面积的函数,

下列 shape 类是一个表示形状的抽象类, area() 为求图形面积的函数, total() 则是一个通用的用以求不同形状的图形面积总和的函数。请从 shape 类派生圆类 (circle) 、矩形类 (rectangle) ,并给出具体的求面积函数。
#include <iostream.h>
  class shape{
  public:
virtual float area( )=0;
  };
  class rectangle:public shape { (6分)
  private:
float upx,upy, width,height;
  public:
rectangle(int x1,int y1,int w,int h)
{upx=x1;upy=y1;width=w;height=h;}
float area() {
return width*height; }
  };
  const float pi=3.14; (6分)
  class circle:public shape {
  private:
float redius;
  public:
circle(float r) { redius=r;}
float area( ) {
return redius*redius*pi; }
  };
  float total(shape *s[],int n) {
float sum=0.0;
for(int i=0;i<n;i++)
sum+=s[i]->area( );
return sum;
  }

每一行都是在干 是什么意思 越详细越好 谢谢

第1个回答  2012-06-08
#include <iostream.h> 宏定义
  class shape{ //定义shape类
  public: // 定义公开的虚方法area,
virtual float area( )=0; //返回值为float型,初值为0
  };
  class rectangle:public shape { // 定义子类rectangle继承于shape
  private: //子类rectangle里定义私有的float型变量
float upx,upy, width,height; //upx,upy, width,height
  public:
rectangle(int x1,int y1,int w,int h) // 四参的构造函数
{upx=x1;upy=y1;width=w;height=h;}
float area() {
return width*height; } // 在rectangle类里重写area方法
  };
  const float pi=3.14; //定义字段pi并赋值为3.14
  class circle:public shape { // 定义shape的子类circle类
  private:
float redius; //定义公开的变量redius(半径)
  public:
circle(float r) { redius=r;} //一参的构造函数
float area( ) {
return redius*redius*pi; } //重写area虚方法
  };
  float total(shape *s[],int n) { //定义total方法,有两个参数
float sum=0.0; //存有类的数组和n
for(int i=0;i<n;i++) //定义变量i从1到n-1循环
sum+=s[i]->area( ); //调用每个类的area方法,把每个返回值想加
return sum; // 返回sum
  }
相似回答