首页 > 代码库 > 【c++程序】抽象类的应用

【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;
	}
}

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