C++面向对象程序设计课后答案6.4

#include "math.h"
#include
using namespace std;
class Shape
{
public : 
 virtual float area( ) const {return 0.0;}
 virtual void shapeName() const=0;
};
class Circle:public Shape
{
public :
 Circle(float r):radius(r){}
 void setRadius(float r)
 {
      radius=r;
   }
      virtual float area() const {return 3.14*radius*radius;}
 virtual void shapeName() const {cout<<"Circle"<  friend ostream & operator <<(ostream &,Circle &);
    private:
      float radius;
};
ostream & operator <<(ostream & output,Circle &c)
{
output<<"radius="< return output;
}
class Rectangle:public Shape
{
public :
 Rectangle(float a,float b)
 {
     x=a;
y=b;
   }
 void setRect(float a,float b)
 {
     x=a;
y=b;
   }
      virtual float area() const {return x*y;}
 virtual void shapeName() const {cout<<"Rectangle"<  friend ostream & operator <<(ostream &,Rectangle &);
    private:
      float x;
      float y;
};
ostream & operator <<(ostream & output,Rectangle &r)
{
output<<"x="< return output;
}
class Triangle:public Shape
{
public :
 Triangle(float a,float b,float c)
 {
     x=a;
y=b;
z=c;
   }
 void setTri(float a,float b,float c)
 {
     x=a;
y=b;
z=c;
   }
      virtual float area() const 
 {
  float s=0;
  float sum=0;
    if((x+y>z)&&(x+z>y)&&(y+z)>x)
    {
          s=(x+y+z)/2;
          sum=sqrt(s*(s-x)*(s-y)*(s-z));
          return sum;
      }
      else
      {
      cout<<"can not shape triangle"<       return 0;
      }
 }
 virtual void shapeName() const {cout<<"Triangle"<  friend ostream & operator <<(ostream &,Triangle &);
    private:
      float x;
      float y;
      float z;
};
ostream & operator <<(ostream & output,Triangle &t)
{
output<<"x="< return output;
}
int main ()
{
float sum=0;
Shape *p;
   Circle c(5);
   c.shapeName();
   cout<    p=&c;
   sum=sum+p->area();
   Rectangle r(3,4);
   r.shapeName();
   cout<    p=&r;
   sum=sum+p->area();
   Triangle t(6,7,8);
   t.shapeName();
   cout<    p=&t;
   sum=sum+p->area();
   cout<<"sum ="<    c.setRadius(10);
   cout<    r.setRect(5,8);
   cout<    t.setTri(3,4,5);
   cout<    return 0;
}

你可能感兴趣的:(C++面向对象程序设计课后答案6.4)