应用抽象类,求圆,圆内切正方形和圆外切正方形的面积和周长,用c++
时间: 2024-12-23 19:18:09 浏览: 8
在C++中,可以创建一个抽象类`Circle`,然后定义其属性如半径以及一些抽象方法,比如计算面积和周长。对于圆内切正方形和圆外切正方形的问题,我们可以再定义两个从`Circle`派生的类,`SquareInsideCircle`和`SquareOutsideCircle`,分别表示这两个情况。
首先,我们创建一个抽象类`Circle`:
```cpp
#include <iostream>
#include <cmath>
class Circle {
public:
abstract double getRadius(); // 纯虚函数,返回半径
virtual double getArea() const = 0; // 抽象方法,返回面积
virtual double getCircumference() const = 0; // 抽象方法,返回周长
protected:
double radius;
};
```
接着,定义派生类:
```cpp
class SquareInsideCircle : public Circle {
private:
double sideLength;
public:
SquareInsideCircle(double r) : Circle(r), sideLength(2 * sqrt(2) * r) {} // 正方形边长与圆直径的关系
double getArea() override { return sideLength * sideLength; }
double getCircumference() override { return Circle::getCircumference(); }
};
class SquareOutsideCircle : public Circle {
private:
double sideLength;
public:
SquareOutsideCircle(double r) : Circle(r), sideLength(2 * r + 2 * sqrt(2) * r) {} // 正方形边长大于圆直径加上直径
double getArea() override { return sideLength * sideLength; }
double getCircumference() override { return Circle::getCircumference(); }
};
```
现在你可以实例化并计算它们的面积和周长:
```cpp
int main() {
Circle* insideCircle = new SquareInsideCircle(5.0);
Circle* outsideCircle = new SquareOutsideCircle(5.0);
std::cout << "圆内切正方形的面积: " << insideCircle->getArea() << "\n";
std::cout << "圆内切正方形的周长: " << insideCircle->getCircumference() << "\n";
std::cout << "圆外切正方形的面积: " << outsideCircle->getArea() << "\n";
std::cout << "圆外切正方形的周长: " << outsideCircle->getCircumference() << "\n";
delete insideCircle;
delete outsideCircle;
return 0;
}
```
阅读全文