利用visual c++1. 程序设计题:设计一个类CRectangle,除了有相关的数据成员外,该类还要求包含以下成员函数:矩形从一个位置移动到另一个位置的Move()函数;改变矩形大小的Size()函数;返回矩形左上角的坐标值的Where()函数;计算矩形面积的Area()函数。
时间: 2023-05-14 21:05:56 浏览: 120
下面是CRectangle类的代码:
```c++
class CRectangle {
public:
CRectangle(int x, int y, int w, int h) : m_x(x), m_y(y), m_w(w), m_h(h) {}
void Move(int x, int y) {
m_x += x;
m_y += y;
}
void Size(int w, int h) {
m_w = w;
m_h = h;
}
int Where() const {
return m_x + m_y;
}
int Area() const {
return m_w * m_h;
}
private:
int m_x, m_y, m_w, m_h;
};
```
这个类包含了矩形的位置和大小信息,并提供了移动、改变大小、获取位置和计算面积的函数。
相关问题
1. 程序设计题:设计一个类CRectangle,除了有相关的数据成员外,该类还要求包含以下成员函数:矩形从一个位置移动到另一个位置的Move()函数;改变矩形大小的Size()函数;返回矩形左上角的坐标值的Where()函数;计算矩形面积的Area()函数。
好的,这是一个典型的面向对象编程问题。以下是一个可能的CRectangle类的实现:
```
class CRectangle {
public:
// 构造函数
CRectangle(int x, int y, int w, int h) : m_x(x), m_y(y), m_w(w), m_h(h) {}
// 移动矩形到新的位置
void Move(int x, int y) {
m_x = x;
m_y = y;
}
// 改变矩形的大小
void Size(int w, int h) {
m_w = w;
m_h = h;
}
// 返回矩形左上角的坐标值
std::pair<int, int> Where() const {
return std::make_pair(m_x, m_y);
}
// 计算矩形面积
int Area() const {
return m_w * m_h;
}
private:
int m_x, m_y; // 矩形左上角的坐标
int m_w, m_h; // 矩形的宽度和高度
};
```
这个类有四个成员函数,分别实现了移动、改变大小、返回坐标和计算面积的功能。其中,构造函数用于初始化矩形的位置和大小。注意,这里使用了一个std::pair来返回坐标值,这是一种简单的方式,也可以使用一个自定义的类来表示坐标。
c++设计完整函数,1. 程序设计题:设计一个类CRectangle,除了有相关的数据成员外,该类还要求包含以下成员函数:矩形从一个位置移动到另一个位置的Move()函数;改变矩形大小的Size()函数;返回矩形左上角的坐标值的Where()函数;计算矩形面积的Area()函数。
以下是CRectangle类的完整代码:
class CRectangle {
private:
int m_left;
int m_top;
int m_right;
int m_bottom;
public:
CRectangle(int left, int top, int right, int bottom) {
m_left = left;
m_top = top;
m_right = right;
m_bottom = bottom;
}
void Move(int x, int y) {
m_left += x;
m_top += y;
m_right += x;
m_bottom += y;
}
void Size(int width, int height) {
m_right = m_left + width;
m_bottom = m_top + height;
}
int* Where() {
int* pos = new int[2];
pos[0] = m_left;
pos[1] = m_top;
return pos;
}
int Area() {
return (m_right - m_left) * (m_bottom - m_top);
}
};
使用示例:
CRectangle rect(0, 0, 10, 10);
rect.Move(5, 5);
rect.Size(20, 20);
int* pos = rect.Where();
int area = rect.Area();
注意:在使用Where()函数返回坐标值时,需要手动释放返回的指针,以避免内存泄漏。