c++的操作符号重载

  • 什么是操作符:

操作符的本质就是代替函数执行任务的符号。有运算符号加减乘除等基础数学操作符,还有解引用,取地址符号,其中new和delete也是操作符的一种,c++中有很多操作符,它们的本质就是调用函数或者方法所有的符号代替实现的功能的都叫做操作符,操作符自身也就是一个函数,也包括我们使用的 大括号 小括号 逗号 尖括号(左移操作和右移操作等)。

  • 重载操作符:

重载操作符就是重新去定义操作符,扩充它的功能,或者重新给他一个新的含义等操作方法,是一个非常有用的操作方法,在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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>

struct Vector2
{
float x,y;
Vector2(float x, float y)
:x(x),y(y){}

Vector2 Multiply(const Vector2& other)
{
return Vector2(x*other.x,y*other.y);
}

Vector2 Add(const Vector2& other) const
{
return Vector2(x+other.x,y+other.y);
}

Vector2 operator+(const Vector2& other) const //重载了加号
{
return Add(other)
}

Vector2 operator*(const Vector2& other) const //重载了乘号
{
return Multiply(other)
}

//对==的重载
bool operator==(const Vector2& other) const
{
return other.x==x && other.y==y;
}
//在==重载基础上重载!=
bool operator==(const Vector2& other) const
{
return !(*this==other);
}
};

//重构操作符(因为在类外面所以要定义一个引入类的操作符)
std::ostream& operator<<(std::ostream& stream,const Vector2& other)
{//ostream指的是输出流
stream << other.x << "," << other.y << std::endl;
return stream;
}

int main()
{
Vector2 a_speed(10.0f,10.0f);
Vector2 speed(0.5f,0.5f);
Vector2 powerup(1.1f,1.1f)
Vector2 final_speed1=a_speed + speed * powerup;
Vector2 final_speed2=a_speed + speed * powerup + speed;
//所以最终速度应该为10*1.1+0.5;
//通过重构的操作符<<直接输出实例的值
std::cout << final_speed << std::endl;
if(final_speed1==final_speed2)
if(final_speed1!=final_speed2)
}

重载操作符就是赋予符合额外的功能,在py中更接近于魔术方法,但是仅限于在类中使用,但是在cpp中可以任何地方使用并且有完全的权限去更改它。


资料参考:

youtube上the cherno的cpp系列