【c++程序】抽象类的应用

#include<iostream>
using namespace std;
class Shape
{
public:
	virtual double area()=0;//纯虚函数
};
class Trigon:public Shape 
{
public:
	Trigon(double H,double W)
	{
		h=H;
		w=W;
	}
	double area()
	{
		return h*w/2;
	}
protected:
	double h,w;
};
class Square:public Trigon
{
public:
	Square(double H,double W):Trigon(H,W){}
	double area(){return h*w;}
};
class Cricle:public Shape
{
protected:
	double radius;
public:
	Cricle(double r){radius=r;}
	double area(){return radius*radius*3.14;}
};
int main()
{
	Shape *p;
	int choice=0;
	while(1)
	{
		bool quit=false;
		cout<<"0-quit 1-三角形 2-正方形 3-圆"<<endl;
		cout<<"请选择:";
		cin>>choice;
		switch(choice)
		{
		case 0:quit=true;
			break;
		case 1:p=new Trigon(5.0,6.0);
			cout<<"三角形的面积"<<p->area()<<endl;
			break;
		case 2:p=new Square(70.0,70.0);
			cout<<"正方形的面积"<<p->area()<<endl;
			break;
		case 3:p=new Cricle(9.0);
			cout<<"圆的面积"<<p->area()<<endl;
			break;
		default:cout<<"请输入0-3"<<endl;
			break;
		}
		if(choice<4&&choice>0)
		{
			delete p;
		}
		if(quit)
			break;
	}
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。