c++设计一个类层次,定义一个抽象类--形装,其中包括有求形状的面积的抽象方法。
发布网友
发布时间:2023-05-17 01:43
我来回答
共1个回答
热心网友
时间:2023-09-10 21:27
#include <iostream>
#include <cmath>
using namespace std;
class Shape{
public:
virtual double area()=0;
};
class Triangle:public Shape{
double a,b,c;
public:
Triangle(double x=1,double y=1,double z=1){
a=x; b=y; c=z;
}
double area(){
double p;
p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
};
class Rectangle:public Shape{
double a,b;
public:
Rectangle(double x=1,double y=1){
a=x; b=y;
}
double area(){
return a*b;
}
};
class Circle:public Shape{
double r;
public:
Circle(double x=1){
r=x;
}
double area(){
return 3.14159*r*r;
}
};
void main(){
Triangle tri(3,4,5);
Rectangle rec(10,5);
Circle cir(10);
Shape *p[3]={ &tri, &rec, &cir};
int i;
for(i=0; i<3; i++)
cout <<p[i]->area() <<endl;
return;
}