C++面向对象程序设计实验题

定义一个抽象类,并派生出矩形类和圆形类,二者都有函数计算对象的面积,并写出main()函数进行测试。设矩形对象的长为了8,宽为5;圆形对象的半径为2.8。


#include<iostream>
using namespace std;
#define PI 3.14159
class shape{
public:
    virtual float getPerim() const =0;
    virtual void getName()const{cout<<"shape:";}
    shape(){}
    ~shape(){}
};

class Rectangle:public shape{
public:
    Rectangle(){}
    ~Rectangle(){}
    Rectangle(float l,float w):length(l),width(w){}
    virtual float getPerim() const;
    virtual void getName()const{cout<<"Rectangle:";}
private:
    float length,width;
};
float Rectangle::getPerim() const{
    return length*width;
}

class Circle :public shape{
public:
    Circle(){}
    Circle(float r):radius(r){}
    ~Circle(){}
    virtual float getPerim()const;
    virtual void getName()const{cout<<"Circle:";}
private:
    float radius;

};
float Circle::getPerim()const{
    return PI*radius*radius;
}

int main(){
    shape *sp;
    Circle circle(2.8);
    Rectangle rectangle(8,5);
    /*普通的访问方式,另一种是使用指针实现动态多态
    circle.getName();
    cout<<circle.getPerim()<<endl;
    rectangle.getName();
    cout<<rectangle.getPerim()<<endl;
    */
    sp=&circle;
    sp->getName();
    cout<<sp->getPerim()<<endl;
    sp=&rectangle;
    sp->getName();
    cout<<sp->getPerim()<<endl;

}

img

就是定义矩形类和圆形类,基类是图形类呗

class Graph
{
  public:
    virtual float area() = 0;
};

class Rectangle : public Graph
{
  private:
    float length,width;
  public:
    Rectangle() {}
    Rectangle(float l,float w) {length = l;width = w;}
    float area() {return l*w;}
};

class Circle : public Graph
{
  private:
    float r;
  public:
    Circle() {}
    Circle(float f) {r=f;}
    float area() {return 3.1415926*r*r;}
};

void main()
{
  Rectangle r(8,5);
  float s = r.area();
  cout<<"矩形面积为"<<s<<endl;
  Circle c(2.8);
  s = c.area();
  cout<<"圆面积为"<<s<<endl;
}
class Shape                                                          //抽象类
{
public:
Shape(){cout<<"Shape"<<endl;}
virtual float getArea()=0;                                                    //纯虚函数

virtual float getPerim()=0;                                                 //纯虚函数
virtual ~Shape(){cout<<"~Shape"<<endl;}                     //虚析构
};


class Rectangle:public Shape
{
public:
Rectangle(float i=0,float j=0):m_i(i),m_j(j)
{
cout<<"Rectangle"<<endl; 
}
float getArea()
{

return m_i*m_j;
}
float getPerim()
{
return 2*(m_i+m_j);
}
~Rectangle(){cout<<"~Rectangle"<<endl;}
private:
float m_i;                         //矩形的长
float m_j;                        //矩形的宽
};


class Circle:public Shape
{
public:
Circle(int i=0):m_k(i)
{
cout<<"Circle"<<endl;
}
float getArea()
{
return 3.14*m_k*m_k;
}
float getPerim()
{
return 3.14*2*m_k;
}
~Circle(){cout<<"~Circle"<<endl;}
private:
float m_k;                         //半径
};


void main()
{
Shape *p;
p=new Rectangle(4,7);
cout<<p->getArea()<<endl;
cout<<(*p).getPerim()<<endl;
delete p;
p=new Circle(9);
cout<<p->getArea()<<endl;
cout<<(*p).getPerim()<<endl;
delete p;
p=NULL;
}