您的位置:首页 > 其它

第十三周实验报告(三)

2012-05-15 17:26 281 查看
写一个程序,定义抽象基类Shap,由他派生出的Ciecle类Rectangle类Triangle类。求出总面积。

 

#include <iostream>
using namespace std;
class Shape
{
public :
virtual float area() =0;
};
class Circle:public Shape
{
private :
float radius;
public :
virtual float area ();
Circle (float radius);
};
class Rectangle:public Shape
{
private:
float length;
float wide;
public :
virtual float area ();
Rectangle (float length,float wide);
};

class Triangle:public Shape
{
private :
float  side_length;
float  height;
public :
virtual float area();
Triangle (float side_length,float height);
};

float Circle::area()
{
return 3.14*(radius)*(radius);
}
Circle::Circle(float radius)
{
this->radius=radius;
}
float Rectangle::area()
{
return (length)*(wide);
}
Rectangle::Rectangle(float length,float wide)
{
this->length = length;
this->wide = wide;
}
float Triangle::area()
{
return (side_length)*(height)*(0.5);
}
Triangle::Triangle(float side_lenght,float height)
{
this->side_length = side_lenght;
this-> height = height;
}

int main()
{
Circle c1(12.6),c2(4.9);    //建立Circle类对象c1,c2,参数为圆半径
Rectangle r1(4.5,8.4),r2(5.0,2.5);       //建立Rectangle类对象r1,r2,参数为矩形长、宽
Triangle t1(4.5,8.4),t2(3.4,2.8);    //建立Triangle类对象t1,t2,参数为三角形底边长与高
Shape *pt[6]={&c1,&c2,&r1,&r2,&t1,&t2}; //定义基类指针数组pt,各元素指向一个派生类对象
float areas=0.0;      //areas为总面积
for(int i=0; i<6; i++)
{
areas=areas+pt[i]->area();
}
cout<<"totol of all areas="<<areas<<endl;   //输出总面积
system("pause");
return 0;
}


 



 

 

抽象类是不能被实例化的,所以只能做基类

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  float class system c