C++程序问题
答案:2 悬赏:20
解决时间 2021-03-24 06:21
- 提问者网友:白柏唇蜜
- 2021-03-23 14:44
将Shape基类定义为抽象类,其成员函数GetArea()为虚函数,由Shape类派生出Circle类(圆)和Rectangle类(矩形),并由Rectangle类派生出Square类(正方形),它们都利用GetArea()函数计算图形面积。根据下列调用语句,分别写出各个类的定义,并且成功地调试运行程序
下面是已经给出的主函数:
Shape *s[5];
s[0]=new Circle(2);
s[1]=new Circle(3);
s[2]=new Rectangle(3, 4);
s[3]=new Rectangle(4, 5);
s[4]=new Square(5);
for(int i=0; i<5; i++) cout<GetArea()<整个程序怎么写啊
最佳答案
- 二级知识专家网友:气场征服一切
- 2021-03-23 15:12
#include
using namespace std;
class Shape
{
public:
//Shape();
virtual double GetArea()=0;
//virtual ~Shape();
};
class Circle: public Shape
{
private: double _r;
public:Circle(double a)
{
_r=a;
}
virtual double GetArea()
{
return 3.14*_r*_r;
}
// virtual ~Circle();
};
class Rectangle:public Shape
{
private: double _width;
double _height;
public:Rectangle(double width,double height)
{
_width=width;
_height=height;
}
Rectangle()
{
_width=0;
_height=0;
}
virtual double GetArea()
{
return _width*_height;
}
// virtual ~Rectangle();
};
class Square: public Rectangle
{
private: double _width;
public:Square(double width)
{
_width=width;
}
virtual double GetArea()
{
return _width*_width;
}
// virtual ~Square();
};
void main()
{
Shape *s[5];
s[0]=new Circle(2);
s[1]=new Circle(3);
s[2]=new Rectangle(3, 4);
s[3]=new Rectangle(4, 5);
s[4]=new Square(5);
for(int i=0; i<5; i++) cout<GetArea()<
}
全部回答
- 1楼网友:浪女动了心
- 2021-03-23 16:30
#include
#define PI 3.14
using namespace std;
class Shape
{
public:
virtual double GetArea()
{
return 0.0;
}
};
class Circle:public Shape
{
protected:
double r;
public:
Circle(double r)
{
this->r=r;
}
virtual double GetArea()
{
return PI*r*r;
}
};
class Rectangle:public Shape
{
protected:
double x,y;
public:
Rectangle(double x,double y)
{
this->x=x;
this->y=y;
}
virtual double GetArea()
{
return x*y;
}
};
class Square:public Rectangle
{
public:
Square(double x):Rectangle(x,x)
{
}
virtual double GetArea()
{
return x*y;
}
};
int main()
{
Shape *s[5];
s[0]=new Circle(2);
s[1]=new Circle(3);
s[2]=new Rectangle(3, 4);
s[3]=new Rectangle(4, 5);
s[4]=new Square(5);
for(int i=0; i<5; i++) cout<GetArea()<
我要举报
大家都在看
推荐资讯