Using C++, 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 20:48:20 浏览: 69
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
Sure, here's an implementation of the Shape, Circle, and Rectangle classes in C++:
```c++
#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 << endl;
cout << "Color: " << color << endl;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(string n, string c, double r) : Shape(n, c), radius(r) {}
void show() {
Shape::show();
cout << "Radius: " << radius << endl;
}
};
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(string n, string c, double w, double h) : Shape(n, c), width(w), height(h) {}
void show() {
Shape::show();
cout << "Width: " << width << endl;
cout << "Height: " << height << endl;
}
};
void showShape(const Shape& shape) {
shape.show();
}
int main() {
Circle circle1("Circle 1", "Red", 5.0);
Rectangle rectangle1("Rectangle 1", "Blue", 3.0, 4.0);
Shape* p_shape = &circle1;
showShape(*p_shape);
p_shape = &rectangle1;
showShape(*p_shape);
return 0;
}
```
In this implementation, the Shape class is a base class with two data members: name and color. The Circle and Rectangle classes are subclasses of Shape, and they add additional data members: radius for Circle and width and height for Rectangle. Each class has its own constructor to initialize its data members, and a show() function to display its data members. The show() function in the base class is declared as virtual so that the derived classes can override it.
The global function showShape() takes a Shape object as a parameter and calls its show() function to display its content.
In the main() function, a Circle object and a Rectangle object are defined. A Shape pointer p_shape is first pointed to circle1 and showShape(*p_shape) is called to display the circle's information. Then, p_shape is changed to point to rectangle1, and showShape(*p_shape) is called to display the rectangle's information.
阅读全文