运算符
-
什么是operator(运算符)?基本上就是一种我们用来代替函数执行某种事情的符号。常见运算符如+,-,*,/
-
不仅是数学运算符,也会有其它常用的运算符,比如‘&’,dereference(解引用)运算符,->箭头运算符, += 运算符,取址运算符,左移运算符( << )
-
还有一些其它的你可能根本就没把它当成运算符的东西,比如new 和delete ,它们实际也是运算符。除此之外,逗号也可以是运算符,括号也可以是。
-
overload重载这个术语本质就是给运算符重载赋予新的含义,或者添加参数,或者创建允许在程序中定义或更改运算符的行为。
-
说到底,运算符就是function,就是函数。与其写出函数名add ,你只用写一个+ 这样的运算符就行,有助于让你的代码更干净整洁,可读性更好。
#include<iostream>
struct Vector2
{
float x,y;
Vector2(float x,float y):x(x),y(y){}
Vector2 Add(const Vector2& other)const{
return Vector2(x+other.x, y+other.y);
}
Vector2 Mutiply(const Vector2& other)const{
return Vector2(x*other.x, y*other.y);
}
};
int main()
{
Vector2 position(4.0f,4.0f);
Vector2 speed(0.5f,1.5f);
Vector2 powerup(1.1f,1.1f);
Vector2 result=position.Add(speed.Mutiply(powerup));
std::cin.get();
}
这里result 看起来有点难读,如果在Java这样的语言中这是唯一的方法。不过再C++中我们有运算符重载,这意味着我们可以利用这些运算符,并定义我们自己的运算符。
#include<iostream>
struct Vector2
{
float x,y;
Vector2(float x,float y):x(x),y(y){}
Vector2 Add(const Vector2& other)const{
return Vector2(x+other.x, y+other.y);
}
Vector2 Mutiply(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 Mutiply(other);
}
void ShowResult(){
std::cout<<this->x<<','<<this->y<<std::endl;
}
};
int main()
{
Vector2 position(4.0f,4.0f);
Vector2 speed(0.5f,1.5f);
Vector2 powerup(1.1f,1.1f);
Vector2 result=position.Add(speed.Mutiply(powerup));
result.ShowResult();
Vector2 result2=position+speed*powerup;
result2.ShowResult();
std::cin.get();
}