In a graph system, there is an abstract class Figure, from which five derived classes are derived: Circle, Square, Rectangle, Trapezoid and Triangle. For example, Square has edge length, Rectangle may have length and width data members, Circle may have radius. Trapezoid may have upper bottom, lower bottom, and high data members. In a well-designed system, these classes are derived from a common class Figure. In this system, the Area() function is defined as a virtual function, and the area of these figures is calculated respectively, and the sum of their areas is calculated. In the main function: 1) Use the base class Figure to define an array, and each element is an object (instance) of five derived classes; 2) Output the area of each derived class object; 3) Output the sum of their area; 4) In addition to realizing the above functions, the main function should also include the following files: #include <iostream> #include "Figure.h" #include "Rectangle.h" #include "Trapezoid.h“ #include "Triangle.h" #include "Square.h " #include " Circle.h " using namespace std; int main() { ……; return 0; }
时间: 2024-01-02 18:02:36 浏览: 102
Here is an example implementation of the system you described:
```cpp
#include <iostream>
#include "Figure.h"
#include "Rectangle.h"
#include "Trapezoid.h"
#include "Triangle.h"
#include "Square.h"
#include "Circle.h"
using namespace std;
int main()
{
// Define an array of Figure objects, including objects of derived classes
Figure* figures[5];
figures[0] = new Circle(5);
figures[1] = new Square(4);
figures[2] = new Rectangle(3, 5);
figures[3] = new Trapezoid(2, 5, 4);
figures[4] = new Triangle(4, 6);
// Output the area of each object
for (int i = 0; i < 5; i++)
{
cout << "Area of figure " << (i+1) << ": " << figures[i]->Area() << endl;
}
// Calculate the sum of their areas
double totalArea = 0;
for (int i = 0; i < 5; i++)
{
totalArea += figures[i]->Area();
}
cout << "Total area: " << totalArea << endl;
// Clean up memory
for (int i = 0; i < 5; i++)
{
delete figures[i];
}
return 0;
}
```
In this implementation, we create an array of Figure pointers, and initialize each element with a new instance of a derived class. We then loop through the array, calling the Area() function on each object and outputting the result. Finally, we loop through the array again to calculate the total area by summing up the individual areas. We also clean up the memory allocated for the objects before exiting the program.
阅读全文