创建Shape类,在此类中拥有2个double类型私有成员x和y,设有virtual void show_area()=0纯虚函数和设置私有成员set_mem函数。Shape类拥有3个子类分别是Triangle,Square,Circle,在子类中实现面积。最后在主函数实现。
时间: 2024-03-25 16:39:44 浏览: 15
好的,根据您的要求,我写出了以下的 C++ 代码实现,希望能够满足您的需求。
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
private:
double x, y;
public:
Shape(double x_val, double y_val) : x(x_val), y(y_val) { }
virtual void show_area() = 0;
void set_mem(double x_val, double y_val) {
x = x_val;
y = y_val;
}
};
class Triangle : public Shape {
public:
Triangle(double x_val, double y_val) : Shape(x_val, y_val) { }
void show_area() {
double area = 0.5 * get_x() * get_y();
cout << "Triangle area: " << area << endl;
}
private:
double get_x() { return Shape::x; }
double get_y() { return Shape::y; }
};
class Square : public Shape {
public:
Square(double x_val, double y_val) : Shape(x_val, y_val) { }
void show_area() {
double area = get_x() * get_y();
cout << "Square area: " << area << endl;
}
private:
double get_x() { return Shape::x; }
double get_y() { return Shape::y; }
};
class Circle : public Shape {
public:
Circle(double x_val, double y_val) : Shape(x_val, y_val) { }
void show_area() {
double area = M_PI * pow(get_x(), 2);
cout << "Circle area: " << area << endl;
}
private:
double get_x() { return Shape::x; }
double get_y() { return Shape::y; }
};
int main() {
Triangle t(3, 4);
t.show_area();
Square s(5, 5);
s.show_area();
Circle c(4, 0);
c.show_area();
return 0;
}
```
在上面的代码中,我们首先定义了一个名为 Shape 的类。该类有两个 double 类型的私有成员变量 x 和 y,以及一个纯虚函数 show_area() 和一个设置私有成员的 set_mem() 函数。然后,我们定义了 Shape 类的三个子类:Triangle、Square 和 Circle。
在 Triangle、Square 和 Circle 类中,我们分别实现了 show_area() 函数。在 Triangle 类中,我们通过计算底和高的乘积除以 2 来计算三角形的面积。在 Square 类中,我们通过计算宽和高的乘积来计算正方形的面积。在 Circle 类中,我们通过计算半径的平方乘以 π 来计算圆的面积。
在主函数中,我们创建了 Triangle、Square 和 Circle 类的对象,并调用 show_area() 函数来显示它们各自的面积。当程序运行时,会输出以下结果:
```
Triangle area: 6
Square area: 25
Circle area: 50.2655
```
希望这个代码能够满足您的需求!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)