欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

虚函数应用实例

程序员文章站 2022-07-12 10:34:46
...

这个程序挺好地解释了在指针下,虚函数引导不同派生类操作的过程(我感觉我没在说人话,还是直接上例子吧)

编写程序:定义抽象基类Shape,由它派生出5个派生类:Circle(圆形)、Square(正方形)、Rectangle
(长方形),triangle(三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针
数组。使它的每一个元素指向一个派生类的对象。

#include<iostream>
#include<algorithm>
using namespace std;
class Shape
{
	public:
		virtual double area()
		{
			return 1.00;
		}
};
class Circle:public Shape
{
	double r;
	public:
		Circle(double d):r(d){};
		double area()
		{
			return 3.1415926*r*r;
		}
};
class Square:public Shape
{
	double length;
	public:
		Square(double l):length(l){};
		double area()
		{
			return length*length; 
		}
};
class Rectangle:public Shape
{
	double length,height;
	public:
		Rectangle(double l,double h):length(l),height(h){};
		double area()
		{
			return length*height;
		}
};
class Triangle:public Shape
{
	double di,height;
	public:
		Triangle(double d,double h):di(d),height(h){};
	double area()
	{
		return (height*di)/2;
	}
};
int main()
{
	Shape *p;
	double result=0;
	Circle c(3);
	Square s(12.2);
	Rectangle r(2.3,5);
	Triangle t(3.3,5.6);
	p=&c;result+=p->area();
	p=&s;result+=p->area();
	p=&r;result+=p->area();
	p=&t;result+=p->area();
	cout<<"总面积为:"<<result<<endl;
	return 0;
}