3.创建Shape类,在此类中拥有2个double类型私有成员x和y,设有virtual void show_area()=0纯虚函数和设置私有成员set_mem函数。Shape类拥有3个子类分别是Triangle,Square,Circle,在子类中实现面积。最后在主函数实现。(15分)
时间: 2024-03-24 12:41:24 浏览: 75
下面是一个可能的实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Shape {
protected:
double x, y;
public:
void set_mem(double x, double y) {
this->x = x;
this->y = y;
}
virtual void show_area() = 0;
};
class Triangle : public Shape {
public:
void show_area() {
double area = 0.5 * x * y;
cout << "Triangle area: " << area << endl;
}
};
class Square : public Shape {
public:
void show_area() {
double area = x * y;
cout << "Square area: " << area << endl;
}
};
class Circle : public Shape {
public:
void show_area() {
double area = 3.14 * x * x;
cout << "Circle area: " << area << endl;
}
};
int main() {
Shape* s[3];
s[0] = new Triangle();
s[1] = new Square();
s[2] = new Circle();
s[0]->set_mem(3, 4);
s[1]->set_mem(2, 2);
s[2]->set_mem(5, 0);
for (int i = 0; i < 3; i++) {
s[i]->show_area();
}
return 0;
}
```
这里定义了一个抽象类 `Shape`,其中包含了 `set_mem` 函数和 `show_area` 纯虚函数。`Triangle`、`Square`、`Circle` 继承自 `Shape` 并实现了各自的 `show_area` 函数。在 `main` 函数中创建了一个 `Shape` 类型的指针数组,并通过 `new` 关键字创建了三个具体的对象,并分别调用了它们的 `set_mem` 函数和 `show_area` 函数,得到了它们各自的面积。
阅读全文