。 3.创建Shape类,在此类中拥有2个double类型私有成员x和y,设有virtual void show_area()=0纯虚函数和设置私有成员set_mem函数。Shape类拥有3个子类分别是Triangle,Square,Circle,在子类中实现面积。最后在主函数实现
时间: 2024-03-25 15:39:27 浏览: 19
好的,以下是代码实现:
```c++
#include <iostream>
using namespace std;
class Shape {
private:
double x;
double y;
public:
Shape(double _x, double _y) : x(_x), y(_y) {}
virtual void show_area() = 0;
protected:
void set_mem(double _x, double _y) {
x = _x;
y = _y;
}
};
class Triangle : public Shape {
public:
Triangle(double _x, double _y) : Shape(_x, _y) {}
void show_area() {
double area = 0.5 * Shape::x * Shape::y;
cout << "三角形的面积为:" << area << endl;
}
};
class Square : public Shape {
public:
Square(double _x, double _y) : Shape(_x, _y) {}
void show_area() {
double area = Shape::x * Shape::y;
cout << "正方形的面积为:" << area << endl;
}
};
class Circle : public Shape {
public:
Circle(double _x, double _y) : Shape(_x, _y) {}
void show_area() {
double area = 3.14 * Shape::x * Shape::x;
cout << "圆形的面积为:" << area << endl;
}
};
int main() {
Triangle t(10, 5);
Square s(8, 8);
Circle c(6, 0);
t.show_area();
s.show_area();
c.show_area();
return 0;
}
```
解析:
- Shape类有两个double类型的私有成员变量x和y,有一个纯虚函数show_area(),以及一个设置私有成员变量的函数set_mem();
- Triangle、Square、Circle三个子类都继承自Shape类,但是都需要重写父类的纯虚函数show_area();
- 在子类中分别实现show_area()函数,计算对应图形的面积并输出;
- 在主函数中创建Triangle、Square、Circle三个对象,调用各自的show_area()函数输出面积。