码迷,mamicode.com
首页 > 其他好文 > 详细

运算符重载举例

时间:2014-05-26 15:40:41      阅读:419      评论:0      收藏:0      [点我收藏+]

标签:style   c   class   blog   code   java   

bubuko.com,布布扣
运算符重载举例


1
#include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class T 7 { 8 public: 9 int getAge(); 10 string getName(); 11 setName(string name); 12 setAge(int age); 13 friend T& operator+(T& tL, T& tR); 14 T& operator=(T& tR) 15 { 16 name = tR.getName(); 17 age = tR.getAge(); 18 return *this; 19 } 20 T(){}; 21 ~T(){}; 22 protected: 23 private: 24 string name; 25 int age; 26 }; 27 28 int main(int argc, char* argv[]) 29 { 30 T t1,t2; 31 t1.setAge(10); 32 t2.setAge(20); 33 t1.setName("QQ"); 34 t2.setName("YY"); 35 cout<<t1.getName()<<" is "<<t1.getAge()<<" years old!"<<endl; 36 cout<<t2.getName()<<" is "<<t2.getAge()<<" years old!"<<endl; 37 t2 = t1 = t1+t2; 38 cout<<t1.getName()<<" is "<<t1.getAge()<<" years old!"<<endl; 39 cout<<t2.getName()<<" is "<<t2.getAge()<<" years old!"<<endl; 40 return 0; 41 } 42 43 T& operator+(T& tL, T& tR) 44 { 45 tL.setAge(tL.getAge()+tR.getAge()); 46 tL.setName(tL.getName()+tR.getName()); 47 return tL; 48 } 49 50 int T::getAge() 51 { 52 return age; 53 } 54 55 string T::getName() 56 { 57 return name; 58 } 59 60 T::setAge(int age) 61 { 62 this->age=age; 63 } 64 65 T::setName(string name) 66 { 67 this->name=name; 68 }
bubuko.com,布布扣

 

运算符重载举例,布布扣,bubuko.com

运算符重载举例

标签:style   c   class   blog   code   java   

原文地址:http://www.cnblogs.com/qianqiang129/p/3746313.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!