定义Shape类接口,求三角形类和圆形类的周长和面积
时间: 2023-10-25 09:20:49 浏览: 101
好的,关于定义Shape类接口,可以包含计算周长和面积的纯虚函数,例如:
```
class Shape {
public:
virtual float getPerimeter() const = 0;
virtual float getArea() const = 0;
};
```
接下来,我们分别定义Triangle类和Circle类来实现Shape接口,计算它们的周长和面积。
Triangle类的定义如下:
```
class Triangle : public Shape {
public:
Triangle(float a, float b, float c) : m_a(a), m_b(b), m_c(c) {}
virtual float getPerimeter() const override {
return m_a + m_b + m_c;
}
virtual float getArea() const override {
float p = getPerimeter() / 2;
return std::sqrt(p * (p - m_a) * (p - m_b) * (p - m_c));
}
private:
float m_a, m_b, m_c;
};
```
Circle类的定义如下:
```
class Circle : public Shape {
public:
Circle(float r) : m_r(r) {}
virtual float getPerimeter() const override {
return 2 * PI * m_r;
}
virtual float getArea() const override {
return PI * m_r * m_r;
}
private:
float m_r;
constexpr static float PI = 3.14159f;
};
```
有了Triangle类和Circle类的定义,我们可以像下面这样计算它们的周长和面积:
```
Triangle t(3.0f, 4.0f, 5.0f);
Circle c(2.0f);
std::cout << "Triangle perimeter: " << t.getPerimeter() << std::endl;
std::cout << "Triangle area: " << t.getArea() << std::endl;
std::cout << "Circle perimeter: " << c.getPerimeter() << std::endl;
std::cout << "Circle area: " << c.getArea() << std::endl;
```
输出结果为:
```
Triangle perimeter: 12
Triangle area: 6
Circle perimeter: 12.5664
Circle area: 12.5664
```
希望这个回答对您有所帮助。
阅读全文