&的重載(取地址符操作符的重載和引用的重載)


一、當為取地址操作符重載

  取地址成員函數是“類的六大默認成員函數之一”。其分為兩種,普通取地址操作符和const取地址操作符。

  取地址是什么意思呢?就是返回當前對象的地址,對於成員函數來講,this指針就是它的地址。

  將'&'重載重載為成員函數時,是否需要傳參?

Date* operator&() {
 
}

  '&'運算符是一個單目運算符,且是一個前置單目運算符,可以看到它是不需要傳參的,但我們知道成員函數的第一個參數為this指針,只是無需書寫出來。

【實例】

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Date
 5 {
 6 public:
 7     //構造函數
 8     Date(int year,int month,int day)
 9     {
10         _year = year;
11         _month = month;
12         _day = day;
13     }
14     //拷貝構造函數
15     Date(const Date& d)
16     {
17         _year = d._year;
18         _month = d._month;
19         _day = d._day;
20     }
21 
22     //&操作符重載
23     Date* operator&()
24     {
25         cout << "Date* operator&()" << endl;
26         return this;
27     }
28     //前一個const表明返回值為一個const Date對象的指針,后一個const表明該成員函數為一個常量成員函數
29     //可以被一個常量對象調用
30     //常量對象只能調用常量成員函數,別的成員函數不能調用
31     const Date* operator&() const
32     {
33         cout << "const Date* operator&()" << endl;
34         return this;
35     }
36 private:
37     int _year;
38     int _month;
39     int _day;
40 };
41 
42 int main(int argc,char* argv[])
43 {
44     Date d1(2021,3,7);
45     const Date d2(2021,3,31);
46 
47     Date* pd1 = &d1;
48     const Date* pd2 = &d2;
49     return 0;
50 }

 

   如果不寫這兩個函數,編譯器會幫助默認生成,若無其它操作完全夠用了,因為這兩個函數默認只返回this指針,也沒有其它的操作。如果你有其它需求,可以重載實現,否則不實現也沒有關系。

(二)&也可以是引用的重載

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Date
 5 {
 6 public:
 7     //構造函數
 8     Date(int year,int month,int day)
 9     {
10         _year = year;
11         _month = month;
12         _day = day;
13     }
14     //拷貝構造函數
15     Date(const Date& d)
16     {
17         _year = d._year;
18         _month = d._month;
19         _day = d._day;
20     }
21 
22     //&操作符重載
23     Date* operator&()
24     {
25         cout << "Date* operator&()" << endl;
26         return this;
27     }
28     //前一個const表明返回值為一個const Date對象的指針,后一個const表明該成員函數為一個常量成員函數
29     //可以被一個常量對象調用
30     //常量對象只能調用常量成員函數,別的成員函數不能調用
31     const Date* operator&() const
32     {
33         cout << "const Date* operator&()" << endl;
34         return this;
35     }
36 
37     //int& 引用的重載
38     operator int&()
39     {
40         return _year;
41     }
42 private:
43     int _year;
44     int _month;
45     int _day;
46 };
47 
48 int main(int argc,char* argv[])
49 {
50     Date d1(2021,3,7);
51     const Date d2(2021,3,31);
52 
53     Date* pd1 = &d1;
54     const Date* pd2 = &d2;
55 
56     int& year = d1;
57     cout << "year = " << year << endl;
58     return 0;
59 }

 

   可以看到year值為d1對象中成員變量_year的值。

  個人理解:

int& year = d1;等價於 int& year = (int&)d1;而因為重載了int&,所以返回了成員變量_year的值

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM