定义一个 Shape 抽象类,定义求面积、周长的纯虚函数,由它派生出 圆形类(Circle)和矩形类(Rectangle),各自定义自己的面积和周长函数。在主函 数可通过派生类对象调用相应的成员函数,
时间: 2024-03-26 22:38:46 浏览: 19
好的,下面是 Shape 抽象类的实现:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0; // 求面积的纯虚函数
virtual double perimeter() const = 0; // 求周长的纯虚函数
};
class Circle : public Shape {
private:
double radius; // 半径
public:
Circle(double r) : radius(r) {}
double area() const {
return 3.14159 * radius * radius;
}
double perimeter() const {
return 2 * 3.14159 * radius;
}
};
class Rectangle : public Shape {
private:
double width; // 宽度
double height; // 高度
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const {
return width * height;
}
double perimeter() const {
return 2 * (width + height);
}
};
int main() {
Shape* s1 = new Circle(5.0);
cout << "Circle area = " << s1->area() << endl;
cout << "Circle perimeter = " << s1->perimeter() << endl;
Shape* s2 = new Rectangle(3.0, 4.0);
cout << "Rectangle area = " << s2->area() << endl;
cout << "Rectangle perimeter = " << s2->perimeter() << endl;
delete s1;
delete s2;
return 0;
}
```
这个程序定义了一个 Shape 抽象类,其中定义了求面积和周长的纯虚函数。然后从 Shape 类派生出 Circle 类和 Rectangle 类,各自定义自己的面积和周长函数。在主函数中通过派生类对象调用相应的成员函数进行测试。