1.
#include<iostream>
using namespace std;
#define PI 3.1415926
class Shape{
public:
virtual double area()=0;
};
class Circle:public Shape
{
private:
double radius;
public:
Circle(double a)
{
radius=a;
}
virtual double area()
{
return PI*radius*radius;
}
};
class Square:public Shape
{
private:
double x;
public:
Square(double a)
{
x=a;
}
virtual double area()
{
return x*x;
}
};
class Rectangle:public Shape
{
private:
double l,w;
public:
Rectangle(double a,double b)
{
l=a;
w=b;
}
virtual double area()
{
return l*w;
}
};
class Trapezoid:public Shape
{
private:
double d1,d2,h;
public:
Trapezoid(double a,double b,double c)
{
d1=a;
d2=b;
h=c;
}
virtual double area()
{
return (d1+d2)*h/2;
}
};
class Triangle:public Shape
{
private:
double d,h;
public:
Triangle(double a,double b)
{
d=a;
h=b;
}
virtual double area()
{
return d*h/2;
}
};
int main()
{
double x1,x2,x3,x4,x5,x6,x7,x8,x9;
cin>>x1>>x2>>x3>>x4>>x5>>x6>>x7>>x8>>x9;
Shape*shape[5]={new Circle(x1),new Square(x2),new Rectangle(x3,x4),new Trapezoid(x5,x6,x7),new Triangle(x8,x9)};
double s;
s=shape[0]->area()+shape[1]->area()+shape[2]->area()+shape[3]->area()+shape[4]->area();
cout<<"total of all areas = "<<s;
return 0;
}
2.
#include<iostream>
#include<iomanip>
using namespace std;
class Shape {
public:
virtual void display() = 0;
};
class Circle :public Shape {
double radium;
public:
Circle(double r) :radium(r) {}
virtual void display();
};
class Rectangle :public Shape {
double lenth, width;
public:
Rectangle(double l, double w) :lenth(l), width(w) {}
virtual void display();
};
class Triangle :public Shape {
double high, bottom;
public:
Triangle(double h, double b) :high(h), bottom(b) {}
virtual void display();
};
void Circle::display() {
cout << fixed << setprecision(2) << 3.1415 * radium * radium << endl;;
}
void Rectangle::display() {
cout << fixed << setprecision(2) << lenth * width << endl;
}
void Triangle::display() {
cout << fixed << setprecision(2) << 0.5 * high * bottom << endl;
}
int main()
{
double radium, high, lenth, width, bottom;
cin >> radium >> lenth >> width >> high >> bottom;
Shape* p[3];
p[0] = new Circle(radium);
p[1] = new Rectangle(lenth, width);
p[2] = new Triangle(high, bottom);
for (int i = 0; i < 3; i++) {
p[i]->display();
delete p[i];
}
}
标签:22,area,double,编程,virtual,class,Shape,2023.4,public From: https://www.cnblogs.com/zbl040721/p/17344004.html