定义一个Shape抽象类,在此基础上派生出Rectangle和Circle,二者都有GetArea()函数计算对象的面积,GetPerim()函数计算对象的周长

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LYhani82475/article/details/76280360

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;
}




运行结果:


展开阅读全文

没有更多推荐了,返回首页