1.设有下面关于点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-08 13:08:21 浏览: 176
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
派生出的Rectangle类的定义如下:
```
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 GetTopLeft() { return Point(GetX(), GetY()); }
Point GetBottomRight() { return Point(GetX() + width, GetY() + height); }
private:
int width;
int height;
};
```
测试程序如下:
```
#include <iostream>
using namespace std;
int main() {
Rectangle rect(0, 0, 5, 4);
cout << "Area = " << rect.GetArea() << endl;
cout << "Top-left point = (" << rect.GetX() << "," << rect.GetY() << ")" << endl;
cout << "Bottom-right point = (" << rect.GetBottomRight().GetX() << "," << rect.GetBottomRight().GetY() << ")" << endl;
return 0;
}
```
输出结果如下:
```
Area = 20
Top-left point = (0,0)
Bottom-right point = (5,4)
```
可以看到,矩形的面积是20,左上顶点的坐标为(0,0),右下顶点的坐标为(5,4)。
阅读全文