定义一个基类Shape定义一个基类Shape,在次基础上派生出Rectangle和Circle 10

定义一个基类Shape,在次基础上派生出Rectangle和Circle。,二者都有GetArea()函数计算对象的面积。使用Rectangle类创建一个派生类Squar... 定义一个基类Shape,在次基础上派生出Rectangle和Circle。,二者都有GetArea()函数计算对象的面积。使用Rectangle类创建一个派生类Square.这是我做的不知道怎么改,帮帮忙,马上要交
#include <iostream>
#include <cmath>
#define pi 3.14
using namespace std;

class Shape
{
Shape(){}
~Shape(){}
virtual float GetArea()
{
return -1;
}
};

class Circle:public Shape
{
private:
float r;
public:
Circle(float r1)
{
r=r1;
}
float getArea()
{
return (float)pi*r*r;
}
};

class Rectangle:public Shape
{
private:
float width,height;
public:
Rectangle(float w1,float h1)
{
width=w1;
height=h1;
}
float getArea()
{
return width*height;
}
};

class Square : public Rectangle
{
public:
Square(float len):Rectangle(len,len){};
~Square(){};
float getArea(float len)
{
return len * len;
};
};

void main()
{
Circle circle;
circle(3);
cout<<"圆的面积为: "<<circle.getArea()<<endl;
Rectangle rectangle;
rectangle(4,5);
cout<<"长方形的面积为: "<<rectangle.getArea()<<endl;

}
展开
 我来答
百度网友71562b2
2018-04-08
知道答主
回答量:2
采纳率:0%
帮助的人:1651
展开全部
#include <iostream>//
#include <cmath>//
#define pi 3.14

using namespace std;

class shape
{
public:
virtual float area()=0;
};
class circle:public shape
{
private:
float r;
public:
circle(float r1)
{
r=r1;
}
float area()
{
return (float)pi*r*r;
}
};
class rectangle:public shape
{
private:
float width,height;
public:
rectangle(float w1,float h1)
{
width=w1;height=h1;
}
float area()
{
return width*height;
}
};
class square : public rectangle//其实是一样的,把rectangle当基类
{
public:
square(float len):rectangle(len,len){};
~square(){};
float area(float len)
{
return len * len;
};
};
float total(shape*s[],int n)
{
float sum=0.0;
for(int i=0;i<n;i++)
sum+=s[i]->area();
return sum;
}
int main()
{
shape* s[2];
s[0]=new circle(1);
cout<<s[0]->area()<<endl;
s[1]=new rectangle(2,4);
cout<<s[1]->area()<<endl;
s[ 2 ] = new square( 3 );//类似照写
cout << s[2]->area() << endl;//
cout << total( s, 3 ) << endl;//改为3
for( int i = 0; i < 3; i++ )//释放
{//
delete [] s[ i ];//
}//
system( "pause" );
return 0;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式