定义一个Shape类,利用它作为基类派生出Rectangle、Circle等具体形状类,已知具体形状类均具有两个方法GetArea和GetColor,分别用来得到形状的面积和颜色。最后编写一个测试程序对产生的类的功能进行验证。
时间: 2023-11-13 07:11:50 浏览: 52
这是一个技术问题,可以回答。
在C++中,可以定义Shape类并将其作为基类来派生具体形状类,如Rectangle和Circle。Shape类中可以定义GetArea和GetColor两个虚函数,子类可以根据自身的具体需求进行重写。
例如:
```
class Shape {
protected:
string color;
public:
virtual double GetArea() = 0;
virtual string GetColor() {
return color;
};
};
class Rectangle : public Shape {
private:
double width;
double height;
public:
Rectangle(double w, double h) {
this->width = w;
this->height = h;
this->color = "red";
}
double GetArea() {
return width * height;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
this->radius = r;
this->color = "green";
}
double GetArea() {
return 3.14 * radius * radius;
}
};
int main() {
Shape* rectangle = new Rectangle(2, 3);
Shape* circle = new Circle(5);
cout << "Rectangle area: " << rectangle->GetArea() << ", color: " << rectangle->GetColor() << endl;
cout << "Circle area: " << circle->GetArea() << ", color: " << circle->GetColor() << endl;
delete rectangle;
delete circle;
return 0;
}
```
运行结果:
```
Rectangle area: 6, color: red
Circle area: 78.5, color: green
```
通过这个例子可以看出,继承自Shape基类的Rectangle和Circle类都有GetArea和GetColor方法,并且可以根据自身的需求进行重写。同时,测试程序也验证了各个类的功能。