日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網營銷解決方案
C++基礎之重載賦值運算符

重載賦值運算符

成都創(chuàng)新互聯(lián)是一家專注于成都網站設計、做網站與策劃設計,江孜網站建設哪家好?成都創(chuàng)新互聯(lián)做網站,專注于網站建設十年,網設計領域的專業(yè)建站公司;建站業(yè)務涵蓋:江孜等地區(qū)。江孜做網站價格咨詢:13518219792

為了解決上面的問題,我們應該寫一個特殊的賦值運算符函數(shù)來處理這類問題。當需要為同一個類的兩個對象相互賦值時,就可以重載運算符函數(shù)。這個方法可以解決類的賦值和指針的釋放。

下面的程序中,類中的賦值函數(shù)用new運算符從堆中分配了一個不同的指針,該指針獲取賦值對象中相應的值,然后拷貝給接受賦值的對象。
在類中重載賦值運算符的格式如下:

 
 
  1. void operator = (const Date&) 

后面我們回加以改進。目前,重載的運算符函數(shù)的返回類型為void。它是類總的成員函數(shù),在本程序紅,是Date類的成員函數(shù)。它的函數(shù)名始終是operator =,參數(shù)也始終是同一個類的對象的引用。參數(shù)表示的是源對象,即賦值數(shù)據(jù)的提供者。重載函數(shù)的運算符作為目標對象的成員函數(shù)來使用。

 
 
  1. #include \"iostream.h\"  
  2. #include \"string.h\"  
  3. class Date  
  4. {  
  5. int mo,da,yr;  
  6. char *month;  
  7. public:  
  8. Date(int m=0, int d=0, int y=0);  
  9. ~Date();  
  10. void operator=(const Date&);  
  11. void display() const;  
  12. };  
  13.  
  14. Date::Date(int m, int d, int y)  
  15. {  
  16. static char *mos[] =  
  17. {  
  18. \"January\",\"February\",\"March\",\"April\",\"May\",\"June\",  
  19. \"July\",\"August\",\"September\",\"October\",\"November\",\"December\" 
  20. };  
  21. mo = m; da = d; yr = y;  
  22. if (m != 0)  
  23. {  
  24. month = new char[strlen(mos[m-1])+1];  
  25. strcpy(month, mos[m-1]);  
  26. }  
  27. else month = 0;  
  28. }   
  29. Date::~Date()  
  30. {  
  31. delete [] month;  
  32. }  
  33. void Date::display() const 
  34. {  
  35. if (month!=0) cout<
  36. }  
  37. void Date::operator=(const Date& dt)  
  38. {  
  39. if (this != &dt)   
  40. {  
  41. mo = dt.mo;  
  42. da = dt.da;  
  43. yr = dt.yr;  
  44. delete [] month;  
  45. if (dt.month != 0)  
  46. {  
  47. month = new char [std::strlen(dt.month)+1];  
  48. std::strcpy(month, dt.month);  
  49. }  
  50. else month = 0;  
  51. }  
  52. }  
  53. int main()  
  54. {  
  55. Date birthday(8,11,1979);  
  56. birthday.display();  
  57. Date newday(12,29,2003);  
  58. newday.display();  
  59. newday = birthday;  
  60. newday.display();  
  61. return 0;  

除了為Date類加入了一個重載運算符函數(shù),這個程序和上面的一個程序是相同的。賦值運算符函數(shù)首先取得所需的數(shù)據(jù),然后用delete把原來的month指針所占用的內存返還給堆。接著,如果源對象的month指針已經初始化過,就用new運算符為對象重新分配內存,并把源對象的month字符串拷貝給接受方。

重載的Date類賦值運算符函數(shù)的***個語句比較了源對象的地址和this指針。這個操作取保對象不會自己給自己賦值。

希望通過以上內容對重載運算的介紹,希望能夠給你帶來幫助。


分享文章:C++基礎之重載賦值運算符
分享路徑:http://m.5511xx.com/article/copjedg.html