课前测 父类:point 数据成员 构造函数 求面积函数 子类:Rectangle 数据成员 构造函数 求面积函数 普通函数fun(Point&s) 利用它调用求面积函数
时间: 2023-08-06 07:06:53 浏览: 50
好的,我理解您的问题了。这是一个关于面向对象编程的问题,您想要一个父类 Point 和一个子类 Rectangle,Point 有数据成员和求面积函数,Rectangle 继承自 Point 并且增加了数据成员和求面积函数。另外,您想要一个普通函数 fun,它接受一个 Point 的引用,并且利用它调用求面积函数。那么,我来给您提供一份代码示例:
```cpp
#include <iostream>
using namespace std;
class Point {
protected:
double x, y;
public:
Point(double _x = 0, double _y = 0) : x(_x), y(_y) {}
virtual double area() const { return 0; } // 该函数是虚函数,因为我们将使用多态
};
class Rectangle : public Point {
private:
double width, height;
public:
Rectangle(double _x = 0, double _y = 0, double w = 0, double h = 0) : Point(_x, _y), width(w), height(h) {}
virtual double area() const { return width * height; } // 重写父类的求面积函数
};
void fun(Point& s) {
cout << "The area of this shape is: " << s.area() << endl;
}
int main() {
Rectangle r(0, 0, 2, 3);
fun(r); // 调用普通函数,利用 Point 的引用调用子类 Rectangle 的求面积函数
return 0;
}
```
在这个代码示例中,我们定义了一个父类 Point 和一个子类 Rectangle。Point 有两个数据成员 x 和 y,还有一个虚函数 area,它返回值为 0,因为 Point 没有面积这个属性。Rectangle 继承自 Point,并且增加了两个数据成员 width 和 height,还重写了父类的求面积函数。我们还定义了一个普通函数 fun,它接受一个 Point 的引用,然后调用该对象的求面积函数。在主函数中,我们创建了一个 Rectangle 的对象 r,然后用 fun 函数来调用它的求面积函数。注意,我们传递的是 Point 的引用,但实际上会调用 Rectangle 的求面积函数,这是因为我们使用了多态。