C++结构 & 运算符重载

C++结构 & 运算符重载

被 palabos 倒逼学 C++。

结构

一个有构造函数,有成员函数的结构。返回回一个矩形格子的四个点:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
using namespace std;

struct Box2D {
Box2D() : x0(), x1(), y0(), y1() { }
// 冒号后面对成员进行初始化
Box2D(int x0_, int x1_, int y0_, int y1_)
: x0(x0_), x1(x1_), y0(y0_), y1(y1_)
{ }
/// Return same box, shifted by (deltaX,deltaY)
Box2D shift(int deltaX, int deltaY) const {
return Box2D(x0+deltaX, x1+deltaX, y0+deltaY, y1+deltaY);
// 返回一个结构
}

bool operator==(Box2D const& rhs) const {
return x0 == rhs.x0 && y0 == rhs.y0 &&
x1 == rhs.x1 && y1 == rhs.y1;
} // 运算符重载

int x0, x1, y0, y1;
};

int main()
{
Box2D box = {1,10,2,9};
cout << "box: " << box.x0 << " " << box.x1 << endl;
Box2D box1,box2;
cout << "box1: " << box1.x0 << " " << box1.x1 << endl;
box2 = box.shift(1,2);
cout << "box2: " << box2.x0 << " " << box2.x1 << endl;
box1 = box2;
cout << "box1: " << box1.x0 << " " << box1.x1 << endl;

if (box1 == box2)
{
cout << "There are equal!" << endl;
}

return 0;
}

运算符重载

重载运算符 == : operator == ()

1
2
3
bool operator==(Box2D const& rhs) const {
return x0 == rhs.x0 && y0 == rhs.y0 &&
x1 == rhs.x1 && y1 == rhs.y1;

box1 == box2 其实是 box1.operator(box2)。第一个对象调用方法,第二个对象作为参数。

1
2
3
4
if (box1 == box2)
{
cout << "There are equal!" << endl;
}
作者

缪红林

发布于

2021-06-08

更新于

2021-06-09

许可协议

评论