习题 12.4 写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上。。。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/navicheung/article/details/82829648

C++程序设计(第三版) 谭浩强 习题12.4 个人设计

习题 12.4 写一个程序,定义抽象基类Shape,由它派生出3个派生类:Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。

代码块:

#include <iostream>
#include <iomanip>
using namespace std;
//基类Shape
class Shape
{
public:
	Shape(){}
	virtual ~Shape(){}
	virtual void printArea() const{}
	virtual void shapeName() const =0;
};
class Circle: public Shape
{
public:
	Circle(double r){radius=r;}
	~Circle(){}
	virtual void printArea() const {cout<<setw(8)<<"area="<<3.14159*radius*radius<<endl;}
	virtual void shapeName() const {cout<<"Circle ";}
protected:
	double radius;
};
class Rectangle: public Shape
{
public:
	Rectangle(double a, double b){x=a; y=b;}
	~Rectangle(){}
	virtual void printArea() const {cout<<setw(5)<<"area="<<x*y<<endl;}
	virtual void shapeName() const {cout<<"Rectangle ";}
protected:
	double x, y;
};
class Triangle: public Shape
{
public:
	Triangle(double a, double h){x=a; y=h;}
	~Triangle(){}
	virtual void printArea() const {cout<<setw(6)<<"area="<<(x*y)/2<<endl;}
	virtual void shapeName() const {cout<<"Triangle ";}
protected:
	double x, y;
};
int main()
{
	Circle c(5);
	Rectangle rec(3, 4);
	Triangle tr(4, 5);
	Shape *pt;
	pt=&c;
	pt->shapeName();
	pt->printArea();
	pt=&rec;
	pt->shapeName();
	pt->printArea();
	pt=&tr;
	pt->shapeName();
	pt->printArea();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/navicheung/article/details/82829648
今日推荐