c中struct重载运算符

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)

这里只展示<,>。其它的比较运算符同理。

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值