C++中如何声明一个抽象类Shape?

2025-04-05 21:57:58
推荐回答(3个)
回答1:

希望你有用。
#include
class Sharp
{
public:
Sharp(){}
~Sharp(){}
virtual float GetArea()=0;
virtual float GetPerim()=0;
};
class Rectangle:public Sharp
{
public:
Rectangle(float len,float width):itsLength(len),itsWidth(width){};
~Rectangle();
virtual float GetArea(){return itsLength*itsWidth;}
float GetPerim(){return 2*itsLength+2*itsWidth;}
virtual float GetLength(){return itsLength;}
virtual float GetWidth(){return itsWidth;}
private:
float itsLength;
float itsWidth;
};
class Circle:public Sharp
{
public:
Circle(float radius):itsRadius(radius){}
~Circle(){}
float GetArea(){return 3.14*itsRadius*itsRadius;}
float GetPerim(){return 6.28*itsRadius;}
private:
float itsRadius;
};
void main()
{
Sharp *sp;
sp=new Circle(5);
cout<<"The area of the Circle is"<GetArea()< cout<<"The perimeter of the Circle is "<GetPerim()< delete sp;
sp=new Rectangle(4,6);
cout<<"The area of the Rectangle is"<GetArea()< cout<<"The perimeter of the Rectangle is "<GetPerim()< delete sp;
}

回答2:

。。。。。。。。
声明一个Shape类,具有纯虚函数getArea和getPerim,Rectangle和Circle的数据成员自己随便添加。
然后就可以了撒。很简单。

回答3:

class Sharp
{
public:
Sharp(double area,double perim)
:Area(area),Perim(perim){}
virtual float GetArea()=0;
virtual float GetPerim()=0;
!Sharp(){}
private:
double Area;
double Perim;
};