结构体运算符重载
来源:互联网 发布:糖尿病网络咨询医生 编辑:程序博客网 时间: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
- 结构体运算符重载
- 结构体运算符重载
- 结构体运算符重载
- 结构体运算符重载
- 结构体中运算符的重载
- 结构体中运算符的重载
- 利用运算符重载将结构体排序--uva11729
- 友元类 运算符重载 new结构体数组
- 结构体 重载运算符模板 + 具体数据类型
- 结构(公有类)的运算符重载
- c/c++中如何写结构体的 构造函数 和 重载运算符?
- 结构体作为map的key或放入set中,需要重载<运算符
- 结构体作为map的key或放入set中,需要重载<运算符
- C++结构体:默认构造函数,复制构造函数,重载=运算符
- C++重载加号运算符实现两个结构体的相加
- C++结构体:默认构造函数,复制构造函数,重载=运算符
- 结构体如果没有重载比较运算符,不能直接进行比较
- set容器中放入结构体时需要重载运算符<
- noip2003神经网络【Pascal】
- SQL反模式--读书笔记--单纯的树(1)
- 编译安装libimobiledevice
- [校内模拟]YL杯超级篮球赛(中位数)
- 161111
- 结构体运算符重载
- #早安,努力#11.12
- jzoj4882 多段线性函数
- ubuntu终端字体大小和窗口大小设置
- 泛型
- bzoj 4717: 改装 二分+set
- tiptop中如何完成即时通讯
- git bash中文乱码问题解决办法
- 最优化中的牛顿法,二阶收敛性