2. 定义一个Point类表示平面上的一个点,再定义一个Rectangle类表示矩形。Rectangle中包含Point类的对象,作为矩形左上角的坐标。要求为Rectangle类创建带参数的构造函数,并在其中初始化Point类的内嵌对象。
时间: 2023-06-10 11:07:54 浏览: 99
下面是代码示例:
```C++
class Point {
public:
double x, y;
Point(double x_coord = 0.0, double y_coord = 0.0) : x(x_coord), y(y_coord) {}
};
class Rectangle {
public:
Point topleft;
Rectangle(double x_coord = 0.0, double y_coord = 0.0) : topleft(Point(x_coord, y_coord)) {}
};
```
在上面的代码中,Point类表示平面上的一个点,包含x和y坐标。Rectangle类表示矩形,包含一个Point对象,作为矩形左上角的坐标。在Rectangle类的构造函数中,通过调用Point类的构造函数来初始化Point对象。如果没有提供x和y坐标,则默认为0.0。
相关问题
2. 定义一个Point类表示平面上的一个点,再定义一个Rectangle类表示矩形。Rectangle中包含Point类的对象,作为矩形左上角的坐标。要求为Rectangle类创建带参数的构造函数,并在其中初始化Point类的内嵌对象。
下面是Point类和Rectangle类的实现:
```cpp
class Point {
public:
Point(int x = 0, int y = 0) : x(x), y(y) {}
int getX() const { return x; }
int getY() const { return y; }
private:
int x, y;
};
class Rectangle {
public:
Rectangle(int x = 0, int y = 0, int w = 0, int h = 0)
: topLeft(x, y), width(w), height(h) {}
int getWidth() const { return width; }
int getHeight() const { return height; }
Point getTopLeft() const { return topLeft; }
private:
Point topLeft;
int width, height;
};
```
在Rectangle类的构造函数中,我们利用了Point类的构造函数来初始化内嵌对象topLeft。这样,我们就可以通过Rectangle类的getTopLeft()函数获取矩形的左上角坐标,通过getWidth()和getHeight()函数获取矩形的宽度和高度了。
定义一个Point类,派生出Rectangle类和Circle类
好的,以下是定义一个Point类,派生出Rectangle类和Circle类的C++代码:
```c++
class Point {
private:
double x;
double y;
public:
Point(double x, double y) : x(x), y(y) {}
double getX() const { return x; }
double getY() const { return y; }
};
class Rectangle : public Point {
private:
double width;
double height;
public:
Rectangle(double x, double y, double width, double height) : Point(x, y), width(width), height(height) {}
double getWidth() const { return width; }
double getHeight() const { return height; }
};
class Circle : public Point {
private:
double radius;
public:
Circle(double x, double y, double radius) : Point(x, y), radius(radius) {}
double getRadius() const { return radius; }
};
```
在这个代码中,Point类表示平面上的一个点,包含x和y坐标。Rectangle类和Circle类都派生自Point类,表示平面上的一个矩形和一个圆形。Rectangle类包含width和height两个属性,表示矩形的宽和高;Circle类包含radius属性,表示圆形的半径。