求大神帮助!用c++编写程序: 定义抽象基类Shape,由它派生出三个派生类:Circle(圆形)
求大神帮助!用c++编写程序:定义抽象基类Shape,由它派生出三个派生类:Circle(圆形)、Square(正方形)、Triangle(三角形),用虚函数分别计算各种...
求大神帮助!用c++编写程序: 定义抽象基类Shape,由它派生出三个派生类:Circle(圆形)、Square(正方形)、Triangle(三角形),用虚函数分别计算各种图形的面积,并求出它们的和。要求用基类指针数组,使它的每一个元素指向一个派生类的对象
展开
1个回答
展开全部
#include<iostream>
#include<cmath>
using namespace std;
const double PI=3.1415927;
class Shape{
public:
virtual double area()=0;
};
class Circle : public Shape{
double radius;
public:
Circle(double r=1){ radius=r; }
double area(){ return PI*radius*radius; }
};
class Square : public Shape{
double length;
public:
Square(double len=1){ length=len; }
double area(){ return length*length; }
};
class Triangle : public Shape{
double a,b,c;
public:
Triangle(double x=3,double y=4,double z=5){
a=x; b=y; c=z;
}
double area(){
double p;
p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c)); }
};
void main(){
Shape *p[3];
Circle c(10);
Square s(20);
Triangle t;
p[0]=&c;
p[1]=&s;
p[2]=&t;
int i;
double a,sum=0;
for(i=0; i<3; i++){
a=p[i]->area();
sum+=a;
cout <<a <<" ";
}
cout <<"\n sum=" <<sum <<endl;
}
#include<cmath>
using namespace std;
const double PI=3.1415927;
class Shape{
public:
virtual double area()=0;
};
class Circle : public Shape{
double radius;
public:
Circle(double r=1){ radius=r; }
double area(){ return PI*radius*radius; }
};
class Square : public Shape{
double length;
public:
Square(double len=1){ length=len; }
double area(){ return length*length; }
};
class Triangle : public Shape{
double a,b,c;
public:
Triangle(double x=3,double y=4,double z=5){
a=x; b=y; c=z;
}
double area(){
double p;
p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c)); }
};
void main(){
Shape *p[3];
Circle c(10);
Square s(20);
Triangle t;
p[0]=&c;
p[1]=&s;
p[2]=&t;
int i;
double a,sum=0;
for(i=0; i<3; i++){
a=p[i]->area();
sum+=a;
cout <<a <<" ";
}
cout <<"\n sum=" <<sum <<endl;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |