首页 > 试题广场 >

定义一个 Shape 基类,在此基础上派生出 Rectan

[问答题]

定义一个 Shape 基类,在此基础上派生出 Rectangle Circle,二者都有 GetArea()函数计算对象的面积。使用 Rectangle 类创建一个派生类 Square

推荐

解:

源程序:

#include <iostream.h>
class Shape
{
public:
Shape(){}
~Shape(){}
virtual float GetArea() { return -1; }
};
class Circle : public Shape
{
public:
Circle(float radius):itsRadius(radius){}
~Circle(){}
float GetArea() { return 3.14 * itsRadius * itsRadius; }
private:
float itsRadius;
};
class Rectangle : public Shape
{
public:
Rectangle(float len, float width): itsLength(len), itsWidth(width){};
~Rectangle(){};
virtual float GetArea() { return itsLength * itsWidth; }
virtual float GetLength() { return itsLength; }
virtual float GetWidth() { return itsWidth; }
private:
float itsWidth;
float itsLength;
};
class Square : public Rectangle
{
public:
Square(float len);
~Square(){}
};
Square::Square(float len);
Rectangle(len,len)
{
}
void main()
{
Shape * sp;
sp = new Circle(5);
cout << "The area of the Circle is " << sp->GetArea () << endl;
delete sp;
sp = new Rectangle(4,6);
cout << "The area of the Rectangle is " << sp->GetArea() << endl;
delete sp;
sp = new Square(5);
cout << "The area of the Square is " << sp->GetArea() << endl;
delete sp;
}

程序运行输出:

The area of the Circle is 78.5

The area of the Rectangle is 24

The area of the Square is 25



发表于 2018-04-18 20:46:56 回复(0)