Table of Contents
#custom-toc-container
C++运算符及其重载
# C++运算符 运算符(操作符,operator),如+、-、&、<<、>>。 在C++中,运算符也是函数(运算符就是函数),不需要函数名。 # C++运算符重载 运算符重载(Operator Overloading):在C++代码中,给运算符赋予新的含义(功能)。 ```cpp class A { private: float x, y; public: A(flaot x, float y) : x(x), y(y) {} A add(const A& other) const { return *this + other; // 这样可以 // return operator+(other); // 这样也可以 } A operator+(const A& other) const { return A(x+other.x, y+other.y); } A multiply(const A& other) const { return A(x*other.x, y*other.y); } A operator*(const A& other) const { return multiply(other); } bool operator==(const A& other) const { return x==other.x && y==other.y; } bool operator!=(const A& other) const { return !(*this==other); } }; ```