c++求图形圆类 正方形类三角形类周长和面积基类派生
时间: 2023-12-08 20:05:02 浏览: 50
好的,以下是一个简单的实现:
```c++
#include<iostream>
using namespace std;
class Shape {
public:
virtual double getArea() = 0;
virtual double getPerimeter() = 0;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double radius) {
this->radius = radius;
}
virtual double getArea() {
return radius * radius * 3.14;
}
virtual double getPerimeter() {
return 2 * radius * 3.14;
}
};
class Square : public Shape {
private:
double side;
public:
Square(double side) {
this->side = side;
}
virtual double getArea() {
return side * side;
}
virtual double getPerimeter() {
return 4 * side;
}
};
class Triangle : public Shape {
private:
double a, b, c;
public:
Triangle(double a, double b, double c) {
this->a = a;
this->b = b;
this->c = c;
}
virtual double getArea() {
double p = (a + b + c) / 2;
return sqrt(p * (p - a) * (p - b) * (p - c));
}
virtual double getPerimeter() {
return a + b + c;
}
};
int main() {
Shape* s1 = new Circle(5);
Shape* s2 = new Square(4);
Shape* s3 = new Triangle(3, 4, 5);
cout << "Circle area: " << s1->getArea() << ", perimeter: " << s1->getPerimeter() << endl;
cout << "Square area: " << s2->getArea() << ", perimeter: " << s2->getPerimeter() << endl;
cout << "Triangle area: " << s3->getArea() << ", perimeter: " << s3->getPerimeter() << endl;
delete s1;
delete s2;
delete s3;
return 0;
}
```
这个例子中,我们定义了一个抽象基类 Shape,其中包含了纯虚函数 getArea() 和 getPerimeter()。然后,我们定义了三个派生类 Circle、Square 和 Triangle。每个派生类都实现了基类 Shape 中定义的两个纯虚函数。在 main 函数中,我们创建了三个 Shape 指针,分别指向 Circle、Square 和 Triangle 类型的对象,并调用它们的 getArea() 和 getPerimeter() 函数。最后,我们使用 delete 运算符释放了这些指针所指向的内存,以防止内存泄漏。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)