编写计算正方形、长方形、圆形的面积和周长的类。要求:(1)这三个类有一个公共的基类。(2)这三个类计算正方形、长方形、圆形的面积和周长的的成员函数名字相同。(3)按照运行时的多态性方法设计一个测试主函数,并进行测试。
时间: 2024-02-09 21:12:06 浏览: 27
好的,我明白您的问题。以下是基于您的要求编写的代码:
```c++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0;
virtual double perimeter() = 0;
};
class Square : public Shape {
private:
double side;
public:
Square(double s) {
side = s;
}
double area() {
return side * side;
}
double perimeter() {
return 4 * side;
}
};
class Rectangle : public Shape {
private:
double length, width;
public:
Rectangle(double l, double w) {
length = l;
width = w;
}
double area() {
return length * width;
}
double perimeter() {
return 2 * (length + width);
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double area() {
return 3.14 * radius * radius;
}
double perimeter() {
return 2 * 3.14 * radius;
}
};
int main() {
Shape *s;
Square sq(5);
Rectangle rec(4, 6);
Circle cir(3);
s = &sq;
cout << "Area of square: " << s->area() << endl;
cout << "Perimeter of square: " << s->perimeter() << endl;
s = &rec;
cout << "Area of rectangle: " << s->area() << endl;
cout << "Perimeter of rectangle: " << s->perimeter() << endl;
s = ○
cout << "Area of circle: " << s->area() << endl;
cout << "Circumference of circle: " << s->perimeter() << endl;
return 0;
}
```
在上面的代码中,我们首先定义了一个名为 `Shape` 的抽象类,并在其中声明了两个纯虚函数 `area()` 和 `perimeter()`,这两个函数分别用于计算图形的面积和周长。
然后,我们定义了三个类 `Square`、`Rectangle` 和 `Circle`,它们都继承自 `Shape` 类,并实现了 `area()` 和 `perimeter()` 函数,用于计算正方形、长方形、圆形的面积和周长。
最后,我们在 `main()` 函数中创建了一个名为 `s` 的指向 `Shape` 类的指针,然后依次将其指向正方形、长方形和圆形对象,调用 `area()` 和 `perimeter()` 函数,输出计算结果。
通过运行时的多态性,我们可以在运行时确定 `s` 指向的对象类型,从而调用正确的函数。