c中struct重载运算符
为什么结构体需要重载运算符
首先我看一段代码:
struct node{
int x,y;
node(int x=2,int y=2):x(x),y(y){
}
}
int main(){
node a,b,c;
c = a + b;
cout<<c.x<<" "<<c.y<<endl;
}
运行上述代码会报错:[Error] no match for ‘operator+’ (operand types are ‘node’ and ‘node’)
因为我们没有定义node结构类型的 + 号,+号不要处理node+node的操作。所以此时我们就需要使用到重载运算符。
具体实现如下:
struct node{
int x,y;
node(int x=2,int y=2):x(x),y(y){
}
node operator + (const node b) const{
node c;
c.x = this->x + b.x;
c.y = this->y + b.y;
return c;
}
}
int main(){
node a,b,c;
c = a + b;
cout<<c.x<<" "<<c.y<<endl;
}
//运行结果 4,4
算术运算符重载
+,-,*,/主要是这四种。+的在上面已实现,其它三个如下:
struct node{
int x,y;
node(int x=2,int y=2):x(x),y(y){
}
node operator + (const node b) const{
node c;
c.x = this->x + b.x;
c.y = this->y + b.y;
return c;
}
node operator - (const node b) const{
node c;
c.x = this->x - b.x;
c.y = this->y - b.y;
return c;
}
node operator * (const node b) const{
node c;
c.x = this->x * b.x;
c.y = this->y * b.y;
return c;
}
node operator / (const node b) const{
node c;
c.x = this->x / b.x;
c.y = this->y / b.y;
return c;
}
};
比较运算符
结构体也是无法进行==,>,<,>=,<=,!=这些操作的,尤其是在使用STL容器的时候,如果我们可以往语句中传入结构体,一些事情将会变得很简单。比如说我们使用优先队列的时候,如何声明结构体的优先队列,如果不写结构体中的比较运算符,程序就会报错。下面来实现如何写struct的比较运算符。
struct node{
int x;
bool operator <(const node b){
return this->x < b.x;
}
bool operator >(const node b){
return this->x > b.x;
}
};
int main(){
node a,b;
a.x=2,b.x=3;
printf("%d",b>a);
}
//输出 1 (1表示true,0表示false)
这里只展示<,>。其它的比较运算符同理。