结构体运算符重载

在Coding中为了方便对可以归根为一个节点的各种属性使用结构体储存,然而使用结构体又不能再随意使用原有的操作符,所以我们要对结构体运算符进行重载,以便使用STL的各种功能比如优先队列
我们举一个栗子
struct Student{
    char name[20];
    bool sex;
    int number;
    int sroce;
};
一个学生包括姓名,性别,学号,分数,如果我们要以分数为优先级越大越靠前(即对分数进行排名) 直接用STL中的优先队列或者快排(也可以手写cmp函数)是不行的,因为两个结构体大小比较没有定义,所有我们可以这样重载运算符“
struct Student{
    char name[20];
    bool sex;
    int number;
    int sroce;
    friend bool operator <(Student a,Student b){
        return a.sroce<b.sroce;
    }
};
Tip:STL优先队列中的优先队列是使用“
struct Money{
    int dollar;
    int pound;
};

这是一个关于钱的结构体
如果我们不重载运算符,实现A中的各元素与B中对于元素相加,貌似只能这样写

struct Money{
    int dollar;
    int pound;
};
Money a,b;
a.dollar+b.dollar;
a.pound+b.pound;

但是如果我们重载了“+”我们就可以直接进行a+b了

struct money{
    int dollar;
    int pound;
    money& operator + (money &vaule){
        dollar+=vaule.dollar;
        pound+=vaule.pound;
        return *this;
    }
};

同理也可以重载“-”

struct money{
    int dollar;
    int pound;
    money& operator - (money &vaule){
        dollar-=vaule.dollar;
        pound-=vaule.pound;
        return *this;
    }
};

但是单独添加这些功能很鸡肋,因为你只能算出他们的和或差,却无法赋值→_→,因为我们没有重载=运算符,根据前面的范例,我们对“=”进行重载

struct money{
    int dollar;
    int pound;
    money& operator + (money &vaule){
        dollar+=vaule.dollar;
        pound+=vaule.pound;
        return *this;
    }
        money& operator - (money &vaule){
        dollar-=vaule.dollar;
        pound-=vaule.pound;
        return *this;
    }
    money& operator = (money &vaule){
        dollar=vaule.dollar;
        pound=vaule.pound;
        return *this;
    }
};

然后我们可以编个小程序测试一下

#include<cstdio>
struct money{
    int dollar;
    int pound;
    money& operator + (money &vaule){
        dollar+=vaule.dollar;
        pound+=vaule.pound;
        return *this;
    }
    money& operator - (money &vaule){
        dollar-=vaule.dollar;
        pound-=vaule.pound;
        return *this;
    }
    money& operator = (money &vaule){
        dollar=vaule.dollar;
        pound=vaule.pound;
        return *this;
    }
}a,b;
int main(){
    a.dollar=3,a.pound=6;
    b.dollar=5,b.pound=2;
    money c=a+b;
    printf("%d %d ",c.dollar,c.pound);
    return 0;
}

程序输出 8 8


于2016/11/8于主站Ozem’s Blog发表,搬运至CSDN

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值