C++ 中的類成員訪問運算子 (->) 過載



類成員訪問運算子 (->) 可以過載,但這比較棘手。它的定義是為了賦予類型別“類似指標”的行為。-> 運算子必須是成員函式。如果使用,它的返回型別必須是指標或可以應用於其上的類的物件。

-> 運算子經常與指標解引用運算子 * 一起使用來實現“智慧指標”。這些指標是行為類似於普通指標的物件,但它們會在您透過它們訪問物件時執行其他任務,例如在指標被銷燬時或指標用於指向另一個物件時自動刪除物件。

解引用運算子 -> 可以定義為一元后綴運算子。也就是說,給定一個類 -

class Ptr {
   //...
   X * operator->();
};

類 **Ptr** 的物件可以用來訪問類 **X** 的成員,其方式與使用指標非常相似。例如 -

void f(Ptr p ) {
   p->m = 10 ; // (p.operator->())->m = 10
}

語句 p->m 被解釋為 (p.operator->())->m。使用相同的概念,以下示例解釋瞭如何過載類訪問運算子 ->。

#include <iostream>
#include <vector>
using namespace std;

// Consider an actual class.
class Obj {
   static int i, j;
   
public:
   void f() const { cout << i++ << endl; }
   void g() const { cout << j++ << endl; }
};

// Static member definitions:
int Obj::i = 10;
int Obj::j = 12;

// Implement a container for the above class
class ObjContainer {
   vector<Obj*> a;

   public:
      void add(Obj* obj) { 
         a.push_back(obj);  // call vector's standard method.
      }
      friend class SmartPointer;
};

// implement smart pointer to access member of Obj class.
class SmartPointer {
   ObjContainer oc;
   int index;
   
   public:
      SmartPointer(ObjContainer& objc) { 
         oc = objc;
         index = 0;
      }
   
      // Return value indicates end of list:
      bool operator++() { // Prefix version 
         if(index >= oc.a.size()) return false;
         if(oc.a[++index] == 0) return false;
         return true;
      }
   
      bool operator++(int) { // Postfix version 
         return operator++();
      }
   
      // overload operator->
      Obj* operator->() const {
         if(!oc.a[index]) {
            cout << "Zero value";
            return (Obj*)0;
         }
      
         return oc.a[index];
      }
};

int main() {
   const int sz = 10;
   Obj o[sz];
   ObjContainer oc;
   
   for(int i = 0; i < sz; i++) {
      oc.add(&o[i]);
   }
   
   SmartPointer sp(oc); // Create an iterator
   do {
      sp->f(); // smart pointer call
      sp->g();
   } while(sp++);
   
   return 0;
}

當編譯並執行上述程式碼時,會產生以下結果:

10
12
11
13
12
14
13
15
14
16
15
17
16
18
17
19
18
20
19
21
cpp_overloading.htm
廣告