c++ rectangle
时间: 2024-06-13 07:04:59 浏览: 81
C++中的rectangle可以有多种实现方式,根据提供的两个引用内容,可以看出一种是使用结构体和类的方式实现的,另一种是使用自定义的rectangle类实现的。下面分别介绍这两种实现方式:
使用结构体和类的方式实现rectangle:
```c++
#include <iostream>
using namespace std;
struct CPoint {
int x;
int y;
};
class CRectangle {
public:
CRectangle(int x1, int y1, int x2, int y2);
CRectangle();
void Init(int x1, int y1, int x2, int y2);
void Move(int dx, int dy);
int GetArea() const;
private:
CPoint m_cLeftTop;
CPoint m_cRightBottom;
};
CRectangle::CRectangle(int x1, int y1, int x2, int y2) {
Init(x1, y1, x2, y2);
}
CRectangle::CRectangle() {
Init(0, 0, 0, 0);
}
void CRectangle::Init(int x1, int y1, int x2, int y2) {
m_cLeftTop.x = x1;
m_cLeftTop.y = y1;
m_cRightBottom.x = x2;
m_cRightBottom.y = y2;
}
void CRectangle::Move(int dx, int dy) {
m_cLeftTop.x += dx;
m_cLeftTop.y += dy;
m_cRightBottom.x += dx;
m_cRightBottom.y += dy;
}
int CRectangle::GetArea() const {
int w = m_cRightBottom.x - m_cLeftTop.x;
int h = m_cRightBottom.y - m_cLeftTop.y;
return w * h;
}
```
使用自定义的rectangle类实现rectangle:
```c++
class rectangle {
public:
rectangle(double x1, double y1, double x2, double y2) {
c1.assign(x1, y1);
c2.assign(x2, y2);
}
double area() {
double w = c2.x - c1.x;
double h = c2.y - c1.y;
return w * h;
}
private:
CPoint c1, c2;
};
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)