C++ 類成員訪問運算符 -> 重載

C++ 重載運算符和重載函數(shù) C++ 重載運算符和重載函數(shù)

類成員訪問運算符( -> )可以被重載,但它較為麻煩。它被定義用于為一個類賦予"指針"行為。運算符 -> 必須是一個成員函數(shù)。如果使用了 -> 運算符,返回類型必須是指針或者是類的對象。

運算符 -> 通常與指針引用運算符 * 結(jié)合使用,用于實現(xiàn)"智能指針"的功能。這些指針是行為與正常指針相似的對象,唯一不同的是,當(dāng)您通過指針訪問對象時,它們會執(zhí)行其他的任務(wù)。比如,當(dāng)指針銷毀時,或者當(dāng)指針指向另一個對象時,會自動刪除對象。

間接引用運算符 -> 可被定義為一個一元后綴運算符。也就是說,給出一個類:

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;

// 假設(shè)一個實際的類
class Obj {
   static int i, j;
public:
   void f() const { cout << i++ << endl; }
   void g() const { cout << j++ << endl; }
};

// 靜態(tài)成員定義
int Obj::i = 10;
int Obj::j = 12;

// 為上面的類實現(xiàn)一個容器
class ObjContainer {
   vector<Obj*> a;
public:
   void add(Obj* obj)
   { 
      a.push_back(obj);  // 調(diào)用向量的標(biāo)準(zhǔn)方法
   }
   friend class SmartPointer;
};

// 實現(xiàn)智能指針,用于訪問類 Obj 的成員
class SmartPointer {
   ObjContainer oc;
   int index;
public:
   SmartPointer(ObjContainer& objc)
   { 
       oc = objc;
       index = 0;
   }
   // 返回值表示列表結(jié)束
   bool operator++() // 前綴版本
   { 
     if(index >= oc.a.size()) return false;
     if(oc.a[++index] == 0) return false;
     return true;
   }
   bool operator++(int) // 后綴版本
   { 
      return 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); // 創(chuàng)建一個迭代器
   do {
      sp->f(); // 智能指針調(diào)用
      sp->g();
   } while(sp++);
   return 0;
}

當(dāng)上面的代碼被編譯和執(zhí)行時,它會產(chǎn)生下列結(jié)果:

10
12
11
13
12
14
13
15
14
16
15
17
16
18
17
19
18
20
19
21

C++ 重載運算符和重載函數(shù) C++ 重載運算符和重載函數(shù)