定义一个Shape抽象类,在此基础上派生出矩形Rectangle(长L=5,宽W=3)和圆形Circle类(半径R=4),二者都有GetPerim()函数计算对象的周长。根据类定义和部分提示代码,完成设计。运行结果下:
提示代码如下:
class Shape//抽象类
{public:
Shape(){}
~Shape(){}
virtual float GetPerim()=0;};//计算图形周长
void main( )
{Shape * sp;
sp=new Circle(4);
......}
构造子类,实现虚函数就可以了啊
class Shape//抽象类
{
public:
Shape(){}
~Shape(){}
virtual float GetPerim()=0;
};
class Rectangle : public Shape
{
public:
Rectangle() {}
Rectangle(float l,float w) : L(l),W(w) {}
~Rectangle() {}
float GetPerim() {return 2*(L+W);}
private:
float L,W;
};
class Circle : public Shape
{
public:
Circle() {}
Circle(float r) : R(r) {}
~Circle() {}
float GetPerim() {return 2*3.1415926*R;}
private:
float R;
};
void main( )
{
Shape * sp;
sp=new Circle(4);
cout<<sp->GetPerim()<<endl;
sp = new Rectangle(5,3);
cout<<sp->GetPerim()<<endl;
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!