C++课后习题

 编写程序,定义抽象类Shape,由它派生出5个派生类:Circle(圆形)  Square(正方形)  Rectangle(长方形)  Trapezoid(梯形)  Triangle(三角形)。用虚函数分别计算几个图形的面积。要求使用基类指针,使其指向派生类对象:

#include<iostream.h>
const double PI=3.14;
class Shape
{
public:
 virtual double area()=0;
 virtual void shapeName()=0;
};
class Circle:public Shape
{
private:
 double r;
public:
 Circle(double rr)
 {
  r=rr;
 }
 virtual double area()
 {
  return PI*r*r;
 }
 virtual void shapeName()
 {
  cout<<"This is a Circle.";
 }
};
class Square:public Shape
{
private:
 double x;
public:
 Square(double xx)
 {
  x=xx;
 }
 virtual double area()
 {
  return x*x;
 }
 virtual void shapeName()
 {
  cout<<"This is a Square.";
 }
};
class Rectangle:public Shape
{
private:
 double x1,y1;
public:
 Rectangle(double m,double n)
 {
  x1=m;
  y1=n;
 }
 virtual double area()
 {
  return x1*y1;
 }
 virtual void shapeName()
 {
  cout<<"This is a Rectangle.";
 }
};
class Trapezoid:public Shape
{
private:
 double x2,y2,h;
public:
 Trapezoid(double a,double b,double hh)
 {
  x2=a;
  y2=b;
  h=hh;
 }
 virtual double area()
 {
  return (x2+y2)*h/2;
 }
 virtual void shapeName()
 {
  cout<<"This is a Trapezoid.";
 }
};
class Triangle:public Shape
{
private:
 double x3,h1;
public:
 Triangle(double e,double d)
 {
  x3=e;
  h1=d;
 }
 virtual double area()
 {
  return x3*h1/2;
 }
 virtual void shapeName()
 {
  cout<<"This is a Triangle.";
 }
};
void main()
{
 Shape *p;
 Circle c(2);
 Square s(3);
 Rectangle cf(6,6);
 Trapezoid t(3,5,4);
 Triangle sj(7,5);
 p=&c;
 p->shapeName();
 cout<<"area="<<p->area()<<endl;
 p=&s;
 p->shapeName();
 cout<<"area="<<p->area()<<endl;
 p=&cf;
 p->shapeName();
 cout<<"area="<<p->area()<<endl;
 p=&t;
 p->shapeName();
 cout<<"area="<<p->area()<<endl;
 p=&sj;
 p->shapeName();
 cout<<"area="<<p->area()<<endl;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值