#include <iostream>
#include <string>
using namespace std;
/*---------------------------------
16-05 6抽象类实例
---------------------------------*/
class shape
{
public:
virtual double area()=0; //纯虚函数
};
class trigon:public shape
{
protected:
double h,w;
public:
trigon(double H,double W)
{
h =H;
w =W;
}
double area(){ return h*w/2;}
};
class square:public trigon
{
public:
square(double H,double W):trigon(H,W){} //直接赋初值
double area(){return h*w;}
};
class circle:public shape
{
protected:
double radius;
public:
circle(double r){radius=r;}
double area(){return radius*radius*3.14;}
};
int main()
{
shape *p;
int choice;
while(1)
{
bool quit=false;
cout<<"0)退出 1)三角形 2)正方形 3)圆: ";
cin>>choice;
switch(choice)
{
case 0:
quit =true;
break;
case 1:
p =new trigon(5,6);
cout<<"三角形的面积为:"<<p->area()<<endl;
delete p;
break;
case 2:
p =new square(5.0, 6);
cout<<"正方形的面积为:"<<p->area()<<endl;
delete p;
break;
case 3:
p =new circle(6);
cout<<"圆的面积为:"<<p->area()<<endl;
delete p;
break;
default:
break;
}
if(quit)
break;
}
return 0;
}
运行结果:
0)退出 1)三角形 2)正方形 3)圆: 1
三角形的面积为:15
0)退出 1)三角形 2)正方形 3)圆: 2
正方形的面积为:30
0)退出 1)三角形 2)正方形 3)圆: 3
圆的面积为:113.04
0)退出 1)三角形 2)正方形 3)圆: 0
Press any key to continue
C++ 多态性 4-- 6抽象类实例
最新推荐文章于 2021-06-29 22:01:25 发布