笔者使用的是Visual Studio2019
如果您使用的是较老版本的Visual Studio或者Visual C++,请在程序结尾处——"return 0;“的上一行加入"system(pause);”。
#include<iostream>
#define PI 3.1415
using namespace std;
class Shape
{
protected:
float area;
public:
void printArea();
virtual void Area();
virtual void ShapeName();
};
class Circle :public Shape
{
private:
float r;
public:
Circle(float b);
virtual void Area();
virtual void ShapeName();
};
class Square :public Shape
{
private:
float l;
public:
Square(float c);
virtual void Area();
virtual void ShapeName();
};
class Rectangle :public Shape
{
private:
float l;
float w;
public:
Rectangle(float c, float k);
virtual void Area();
virtual void ShapeName();
};
class Trapezoid :public Shape
{
private:
float t;
float b;
float h;
public:
Trapezoid(float s, float x, float g);
virtual void Area();
virtual void ShapeName();
};
class Triangle :public Shape
{
private:
float b;
float h;
public:
Triangle(float d, float g);
virtual void Area();
virtual void ShapeName();
};
void Shape::printArea()
{
cout << "area is:" << area << endl;
}
void Shape::Area(){}
void Shape::ShapeName() {}
Circle::Circle(float b)
{
r = b;
}
void Circle::Area()
{
area = PI * r * r;
}
void Circle::ShapeName()
{
cout << "Circle ";
}
Square::Square(float c)
{
l = c;
}
void Square::Area()
{
area = l * l;
}
void Square::ShapeName()
{
cout << "Square ";
}
Rectangle::Rectangle(float c, float k)
{
l = c;
w = k;
}
void Rectangle::Area()
{
area = l * w;
}
void Rectangle::ShapeName()
{
cout << "Rectangle ";
}
Trapezoid::Trapezoid(float s, float x, float g)
{
t = s;
b = x;
h = g;
}
void Trapezoid::Area()
{
area = (t + b) * h / 2;
}
void Trapezoid::ShapeName()
{
cout << "Trapezoid ";
}
Triangle::Triangle(float d, float g)
{
b = d;
h = g;
}
void Triangle::Area()
{
area = b * h / 2;
}
void Triangle::ShapeName()
{
cout << "Triangle ";
}
int main()
{
Circle c(2);
Square s(2);
Rectangle r(2, 3);
Trapezoid tra(2, 2, 2);
Triangle tri(2, 2);
Shape* p[5]={ &c, &s,&r,&tra,&tri };
for (int i = 0; i < 5; i++)
{
p[i]->Area();
p[i]->ShapeName();
p[i]->printArea();
}
return 0;
}
程序写得很拙陋,还望前辈不吝赐教。