C++程序设计(第三版)谭浩强 编著 P400 习题5参考答案

笔者使用的是Visual Studio2019
如果您使用的是较老版本的Visual Studio或者Visual C++,请在程序结尾处——"return 0;“的上一行加入"system(pause);”。

#include<iostream>
#define PI 3.1415
using namespace std;
class Shape
{
protected:
 float area;
public:
 void printArea();
 virtual void Area();
 virtual void ShapeName();
};
class Circle :public Shape
{
private:
 float r;
public:
 Circle(float b);
 virtual void Area();
 virtual void ShapeName();
};
class Square :public Shape
{
private:
 float l;
public:
 Square(float c);
 virtual void Area();
 virtual void ShapeName();
};
class Rectangle :public Shape
{
private:
 float l;
 float w;
public:
 Rectangle(float c, float k);
 virtual void Area();
 virtual void ShapeName();
};
class Trapezoid :public Shape
{
private:
 float t;
 float b;
 float h;
public:
 Trapezoid(float s, float x, float g);
 virtual void Area();
 virtual void ShapeName();
};
class Triangle :public Shape
{
private:
 float b;
 float h;
public:
 Triangle(float d, float g);
 virtual void Area();
 virtual void ShapeName();
};
void Shape::printArea()
{
 cout << "area is:" << area << endl;
}
void Shape::Area(){}
void Shape::ShapeName() {}
Circle::Circle(float b)
{
 r = b;
}
void Circle::Area()
{
 area = PI * r * r;
}
void Circle::ShapeName()
{
 cout << "Circle ";
}
Square::Square(float c)
{
 l = c;
}
void Square::Area()
{
 area = l * l;
}
void Square::ShapeName()
{
 cout << "Square ";
}
Rectangle::Rectangle(float c, float k)
{
 l = c;
 w = k;
}
void Rectangle::Area()
{
 area = l * w;
}
void Rectangle::ShapeName()
{
 cout << "Rectangle ";
}
Trapezoid::Trapezoid(float s, float x, float g)
{
 t = s;
 b = x;
 h = g;
}
void Trapezoid::Area()
{
 area = (t + b) * h / 2;
}
void Trapezoid::ShapeName()
{
 cout << "Trapezoid ";
}
Triangle::Triangle(float d, float g)
{
 b = d;
 h = g;
}
void Triangle::Area()
{
 area = b * h / 2;
}
void Triangle::ShapeName()
{
 cout << "Triangle ";
}
int main()
{
 Circle c(2);
 Square s(2);
 Rectangle r(2, 3);
 Trapezoid tra(2, 2, 2);
 Triangle tri(2, 2);
 Shape* p[5]={ &c, &s,&r,&tra,&tri };
 for (int i = 0; i < 5; i++) 
 {
  p[i]->Area();
  p[i]->ShapeName();
  p[i]->printArea();
 }
 return 0;
}

程序写得很拙陋,还望前辈不吝赐教。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值