C++ 基类指针数组,虚函数

面向对象编程与图形计算:多边形面积计算与输出
本文介绍了如何使用面向对象编程技术实现多边形面积计算,并通过虚函数优化代码结构。具体包括圆形、正方形、矩形、梯形和三角形的面积计算,通过基类指针数组实现对不同多边形对象的操作。

 实验题目:
定义一个抽象基类shape,由它派生5个类:circle,square,rectangle,trapezoid,triangle.

用虚函数分别计算图形的面积,要求用基类指针数组,使他们的每个元素指向一个派生类对象 。

程序如下:


#include<iostream>
#include<math.h>
using namespace std;
class Shape
{
public:
	virtual void ShapeName(){}                   //虚函数
	virtual float area() { return 0.0; }         //虚函数
};

class Circle:public Shape
{
public:
	Circle(float r){ radius = r; }
	virtual void ShapeName() { cout << "Circle area: "; }        //对虚函数再定义
	virtual float area() { return 3.14*radius*radius; }
protected:
	float radius;
};

class Square :public Shape
{
public:
	Square(float s){ side = s; };
	virtual void ShapeName() { cout << "Square area: "; }
	virtual float area(){ return side*side; }
protected:
	float side;
};
class Rectangle :public Shape{
public:
	Rectangle(float a, float b){ length = a; width = b; };
	virtual void ShapeName() { cout << "Rectangle area: "; }
	virtual float area(){ return length*width; }
protected:
	float length;
	float width;
};
class Trapezoid :public Shape{
public:
	Trapezoid(float top, float bottom, float h){ topside = top; bottomside = bottom; high = h; };
	virtual void ShapeName() { cout << "Trapezoid area: "; }
	virtual float area(){ return (topside + bottomside)*high / 2; }
protected:
	float topside;
	float bottomside;
	float high;
};
class Triangle :public Shape{
public:
	Triangle(float a, float b, float c){ sidea = a; sideb = b; sidec = c; };
	virtual void ShapeName() { cout << "Triangle area: "; }
	virtual float area(){ float s = (sidea + sideb + sidec) / 2; float m = s*(s - sidea)*(s - sideb)*(s - sidec); return sqrt(m); }
protected:
	float sidea;
	float sideb;
	float sidec;
};
int main(){
	Circle circle(5);
	Square square(5);
	Rectangle rectangle(2, 3);
	Trapezoid trapezoid(3, 4, 8);
	Triangle triangle(3,4,5);
	Shape *p[5] = { &circle, &square,&rectangle,&trapezoid,&triangle };
	for (int i = 0; i < 5; i++){
		p[i]->ShapeName();
		cout << p[i]->area() << endl;
	}
	system("pause");
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值