类的继承与派生(Shape例子派生Rectangle和Circle,Rectangle派生出Square)

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

#include
#include
using namespace std;

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 itsLength;
    float itsWidth;
};

class Square:public Rectangle
{
public:
    Square(float len);
    ~Square(){};
};

Square::Square(float len):Rectangle(len,len)
{

}
int main()
{
    Shape*sp;
    sp=new Circle(5);
    cout<<"The area of the Circle is"<getArea()<new Rectangle(4,6);
    cout<<"The area of the Rectangle is"<getArea()<new Square(5);
    cout<<"The area of the Square is"<getArea()<return 0;
}

你可能感兴趣的:(C++学习)