Define a Shape class and its subclasses Circle and Rectangle. The detailed requirements are: (1) Data members: a) Shape's data members include: name, color. b) Circle has an additional data member: radius. c) Rectangle has two additional data members: width, height. (2) Member functions: a) Each class should have a constructor to initialize its data members. b) Define in each class a function show() to display its data members. (3) A global function "showShape(const Shape &shape)" to call a Shape object’s show() function t o display its content. (4) The main() function: a) Define a Circle object circle1 and a Rectangle object rectangle1. b) Define a Shape pointer p_shape to point to circle1, and call showShape(*p_shape) to displ ay the circle's information. c) Change p_shape to point to rectangle1, and call showShape(*p_shape) to display the recta ngle's information.
时间: 2024-03-06 13:48:19 浏览: 30
Sure, I can help you with that! Here is the implementation of the Shape class and its subclasses Circle and Rectangle, along with the global function showShape() and the main() function:
```
#include <iostream>
#include <string>
using namespace std;
class Shape {
protected:
string name;
string color;
public:
Shape(string n, string c) : name(n), color(c) {}
virtual void show() {
cout << "Name: " << name << ", Color: " << color << endl;
}
};
class Circle : public Shape {
private:
int radius;
public:
Circle(string n, string c, int r) : Shape(n, c), radius(r) {}
void show() {
Shape::show();
cout << "Radius: " << radius << endl;
}
};
class Rectangle : public Shape {
private:
int width;
int height;
public:
Rectangle(string n, string c, int w, int h) : Shape(n, c), width(w), height(h) {}
void show() {
Shape::show();
cout << "Width: " << width << ", Height: " << height << endl;
}
};
void showShape(const Shape &shape) {
shape.show();
}
int main() {
Circle circle1("Circle 1", "Red", 5);
Rectangle rectangle1("Rectangle 1", "Blue", 10, 8);
Shape *p_shape = &circle1;
showShape(*p_shape);
p_shape = &rectangle1;
showShape(*p_shape);
return 0;
}
```
In this implementation, we have defined the Shape class as a base class with two data members: name and color. We have also defined two subclasses, Circle and Rectangle, with additional data members radius and width/height respectively.
Each class has a constructor to initialize its data members, and a show() function to display its data members.
We have also defined a global function showShape() which takes a Shape object as its argument and calls its show() function to display its content.
Finally, in the main() function, we create a Circle object circle1 and a Rectangle object rectangle1. We then define a Shape pointer p_shape to point to circle1, and call showShape(*p_shape) to display the circle's information. We then change p_shape to point to rectangle1, and call showShape(*p_shape) to display the rectangle's information.