结构体运算符重载

来源:互联网 发布:糖尿病网络咨询医生 编辑:程序博客网 时间:2024/05/21 12:07
在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

0 0
原创粉丝点击