C++中结构体是无法进行+ - * /,==,>,<,>=,<=,!=等运算符操作的,如要使用这些运算符对结构体进行操作,则要对这些运算符进行重载。
/*在结构体中进行运算符重载*/
struct node1
{
int x,y;
bool operator <(const node1 &a)const { //重载<,返回bool类型
if(x==a.x)return y<a.y;
else return x>a.x;
//也可以使用this指针来指向当前这个结构体的成员,要表示这个结构体则用 *this
//if(this->x==a.x)return this->y<a.y;
//else return this->x>a.x;
}
};
struct node2
{
int x,y;
friend bool operator <(const node2 &a,const node2 &b){ //在结构体内重载运算符,添加两个参数需在前面添加friend关键字.
if(a.x==b.x)return a.y<b.y;
else return a.x>b.x;
}
};
/*在结构体外面进行运算符重载,可以添加两个参数,不需要friend关键字.*/
int operator +(const node &a,const node &b){ //重载+,返回int类型
return a.x+b.y;
}