C++ 运算符重载

Java中的字符串String之所以能够相加,其实就是重载了+号运算符。

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
42
43
44
45
46
47
class Point{
public:
int x;
int y;
public:
Point(int x = 0, int y = 0){
this->x = x;
this->y = y;
}

// 采用成员函数,定义运算符
Point operator-(Point &p){
Point temp(this->x - p.x, this->y - p.y);
return temp;
}
};

// 重载运算符+(本质还是函数调用)
// 为了减少中间传递的拷贝,参数使用引用;(也可以用指针,当时运算符使用起来更麻烦,需要使用*)
Point operator+(Point &p1, Point &p2){
Point temp(p1.x + p2.x, p1.y + p2.y);
return temp;
}

// 当属性私有时,重载的运算符无法访问到私有的属性,此时可以通过友元函数来实现
class Point{

// 声明友元函数式的操作符,这样操作符就能够访问私有属性
friend Point operator+(Point& p1, Point& p2){
Point temp(p1.x + p2.x, p1.y + p2.y);
return temp;
}

private:
int x;
int y;
public:
Point(int x, int y){
this->x = x;
this->y = y;
}
};

Point operator+(Point& p1, Point& p2){
Point temp(p1.x + p1.x, p1.y + p2.y);
return temp;
}