运算重载就是在程序中定义操作符或者改变操作符的行为,操作符就像是一个函数,比如定义一个加法函数与使用+操作符是一样的,运算符重载主要用于类对象之间的运算,使得编译器遇到类对象时,能够按照我们定义的方式进行运算。
class entity{
private:
float x,y;
public:
entity(float _x,float _y):x(_x),y(_y){}
entity operator+(const entity &e1) const{
return entity(x + e1.x, y + e1.y);
}
friend void print(const entity &e);
};
void print(const entity &e){
std::cout << e.x << e.y << std::endl;
}
int main(int argc, char const *argv[])
{
entity e0(1.0,2.0);
entity e1(1.5,2.5);
entity result = e0 + e1;
print(result);
return 0;
}