【任务4】设计一个抽象类CSolid,含有两个求表面积及体积的纯虚函数。设计个派生类CCube、CBall、
CCylinder,分别表示正方体、球体及圆柱体。在main()函数中,定义基类的指针p(CSolid *p;),利
运行结果:
CCylinder,分别表示正方体、球体及圆柱体。在main()函数中,定义基类的指针p(CSolid *p;),利
用p指针,输出正方体、球体及圆柱体对象的表面积及体积。
#include<iostream>
using namespace std;
class CSolid
{
public:
virtual float area() const = 0;//表面积函数
virtual float volume() const = 0;//体积函数
};
//定义正方体类,以CSolid为抽象基类
class CCube:public CSolid
{
public:
CCube(float length,float width,float heigth)
{
this -> length = length;
this -> width = width;
this -> heigth = heigth;
}
virtual float area() const;
virtual float volume() const;
protected:
float length;
float width;
float heigth;
};
float CCube::area() const
{
return(length*width+length*heigth+width*heigth)*2;
}
float CCube::volume() const
{
return(length*heigth*width);
}
//定义球体,以CSolid为抽象基类
class CBall:public CSolid
{
public:
CBall(float radius)
{
this -> radius = radius;
}
virtual float area() const;
virtual float volume() const;
protected:
float radius;
};
float CBall::area() const
{
return(4 * 3.14 * radius * radius);
}
float CBall::volume() const
{
return(4/3 * 3.14 * radius * radius * radius);
}
//定义圆柱体类,以CSolid为抽象基类
class CCylinder:public CSolid
{
public:
CCylinder(float radius,float heigth)
{
this -> radius = radius;
this -> heigth = heigth;
}
virtual float area() const;
virtual float volume() const;
protected:
float radius;
float heigth;
};
float CCylinder::area() const
{
return(2 * 3.14 * radius * radius + 2 * 3.14 * radius * heigth);
}
float CCylinder::volume() const
{
return(3.14 * radius * radius * heigth);
}
int main()
{
CSolid *p;
double s,v;
CCube x(5,6,7);
cout<<"长方体的长,宽,高分别为5,6,7"<<endl;
p=&x;
s=p->area( );
v=p->volume( );
cout<<"表面积:"<<s<<endl;
cout<<"体积:"<<v<<endl;
cout<<endl;
CBall y(2.0);
cout<<"球体半径为2.0"<<endl;
p=&y;
s=p->area( );
v=p->volume( );
cout<<"表面积:"<<s<<endl;
cout<<"体积:"<<v<<endl;
cout<<endl;
CCylinder z(2.5,10.0);
cout<<"圆柱体底面半径、高分别为2.5,10.0"<<endl;
p=&z;
s=p->area( );
v=p->volume( );
cout<<"表面积:"<<s<<endl;
cout<<"体积:"<<v<<endl;
cout<<endl;
system("pause");
return 0;
}
运行结果:
长方体的长,宽,高分别为5,6,7
表面积:214
体积:210
球体半径为2.0
表面积:50.24
体积:25.12
圆柱体底面半径、高分别为2.5,10.0
表面积:196.25
体积:196.25
请按任意键继续. . .