设有下面关于点Point类的定义,请在此基础上派生出一个矩形Rectangle类,用以描述矩形的左上角的顶点,并能够计算矩形的面积,并给出测试程序,测试程序里,定义矩形的对象,求出矩形的面积和矩形的位置(即左上顶点和右下顶点的坐标)。 class Point {public: Point(int a,int b){ x=a; y=b;} Point(){x=0;y=0;} int GetY(){return y;} int GetX(){return x;} void SetY(int b){ y=b;} void SetX(int a){ x=a;} private: int x; int y; };
时间: 2023-06-13 10:02:58 浏览: 149
以下是派生出的Rectangle类的定义和测试程序:
```cpp
#include <iostream>
using namespace std;
class Point {
public:
Point(int a, int b) { x = a; y = b; }
Point() { x = 0; y = 0; }
int GetY() { return y; }
int GetX() { return x; }
void SetY(int b) { y = b; }
void SetX(int a) { x = a; }
private:
int x;
int y;
};
class Rectangle : public Point {
public:
Rectangle(int a, int b, int w, int h) : Point(a, b) { width = w; height = h; }
int GetWidth() { return width; }
int GetHeight() { return height; }
void SetWidth(int w) { width = w; }
void SetHeight(int h) { height = h; }
int GetArea() { return width * height; }
Point GetBottomRight() { return Point(GetX() + width, GetY() + height); }
private:
int width;
int height;
};
int main() {
Rectangle rect(0, 0, 5, 10);
cout << "Rectangle area: " << rect.GetArea() << endl;
cout << "Top-left point: (" << rect.GetX() << ", " << rect.GetY() << ")" << endl;
Point bottomRight = rect.GetBottomRight();
cout << "Bottom-right point: (" << bottomRight.GetX() << ", " << bottomRight.GetY() << ")" << endl;
return 0;
}
```
输出结果为:
```
Rectangle area: 50
Top-left point: (0, 0)
Bottom-right point: (5, 10)
```
可以看出,Rectangle类正确地计算了矩形的面积,并且能够获取矩形的左上角和右下角的坐标。
阅读全文