CPP操作符重载
2016-02-23 21:21
204 查看
1在类中重载+=操作符
赋值操作符必须定义为成员函数,无论形参为何种类型赋值必须返回*this 的引用
class Love{ public: int str; int agi; int intel; Love(): str(0), agi(0) , intel(0){} Love(int a , int b ,int c): str(a), agi(b) , intel(c){}; Love& operator+=(const Love &test){ str += test.str; agi += test.agi; intel += test.intel; return *this; } };
int main(){ Love boy ,girl(10,20,30); boy += girl; cout << boy.str << boy.agi << boy.intel << endl; return 0; }
在类外面重载+号
class Love{ public: int str; int agi; int intel; Love(): str(0), agi(0) , intel(0){} Love(int a , int b ,int c): str(a), agi(b) , intel(c){}; }; //为了与内置操作符保持一致,加法返回一个右值,而不是引用 Love operator+(const Love &fir, const Love &sec){ Love ans; ans.str = fir.str + sec.str ; ans.agi = fir.agi + sec.agi ; ans.intel = fir.intel + sec.intel; return ans; }
在类外面的输入输出操作符
为什么IO操作符必须为非成员函数?因为做操作数只能是该类类型的对象
比如 Love item;
item << cout ;
由于IO操作符通常对非公用数据成员进行读写,所以通常将IO操作符
设定为友元 class Love{ public: int str; int agi; int intel; Love(): str(0), agi(0) , intel(0){} Love(int a , int b ,int c): str(a), agi(b) , intel(c){}; friend istream& operator>> (istream& , Love&); friend ostream& operator<< (ostream& , const Love&); }; //要有处理错误和文件结尾的措施 istream& operator>>(istream& in, Love &s){ in >> s.str >> s.agi >> s.intel; if( !in ) Love(0,0,0); return in; } ostream& operator<<(ostream& out ,const Love &s){ out << "str:=" << s.str << " agi:=" << s.agi << " Int:=" << s.intel; return out; }
相关文章推荐
- C++中的操作符重载详细解析
- STL与泛型编程(1)---模板
- CPP 虚函数、虚函数表及虚拟继承(转)
- Deploying Control Plane Policing
- Thrift的required和optional源码分析
- c++中extern关键字详解 知识补充笔记
- MBProgressHUD的基本使用
- 意外的结果-C++中的移位操作
- MFC自定义类访问主窗口控件
- LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main 问题解决
- 单向链表LinkedList的使用
- cpp函数返回对象&&数组
- 继承、组合、委托
- LIB和DLL的区别与使用
- Learn note(cpp): take care when use new in a code block.
- 如果在主串Tag的第pos个位置后存在
- BF算法
- 一个悲伤的gcc故事
- 用gcc编译opencv程序出错
- cocos2d-x-3.2创建项目中出现的一些问题