c++定义一个抽象基类Shape,由它派生出3个派生类:Circle,Square,Rectangle,用一个函数printarea分别输出以上三者的面积,3个图形的数据在定义对象时给定。创建基类指针,指向各个派生类对象
时间: 2024-03-06 08:46:15 浏览: 96
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
好的,下面是 C++ 的代码示例:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14 * radius * radius;
}
private:
double radius;
};
class Square : public Shape {
public:
Square(double s) : side(s) {}
double area() const override {
return side * side;
}
private:
double side;
};
class Rectangle : public Shape {
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() const override {
return length * width;
}
private:
double length;
double width;
};
void printarea(const Shape& shape) {
cout << "The area is " << shape.area() << endl;
}
int main() {
Circle circle(5);
Square square(4);
Rectangle rectangle(3, 6);
printarea(circle);
printarea(square);
printarea(rectangle);
Shape* shape_ptrs[3];
shape_ptrs[0] = new Circle(2);
shape_ptrs[1] = new Square(3);
shape_ptrs[2] = new Rectangle(4, 5);
for (int i = 0; i < 3; i++) {
printarea(*shape_ptrs[i]);
delete shape_ptrs[i];
}
return 0;
}
```
运行结果如下:
```
The area is 78.5
The area is 16
The area is 18
The area is 12.56
The area is 9
The area is 20
```
阅读全文