Latest web development tutorials

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

C++ 重載運算符和重載函數 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;

// 假设一个实际的类
class Obj {
   static int i, j;
public:
   void f() const { cout << i++ << endl; }
   void g() const { cout << j++ << endl; }
};

// 静态成员定义
int Obj::i = 10;
int Obj::j = 12;

// 为上面的类实现一个容器
class ObjContainer {
   vector<Obj*> a;
public:
   void add(Obj* obj)
   { 
      a.push_back(obj);  // 调用向量的标准方法
   }
   friend class SmartPointer;
};

// 实现智能指针,用于访问类 Obj 的成员
class SmartPointer {
   ObjContainer oc;
   int index;
public:
   SmartPointer(ObjContainer& objc)
   { 
       oc = objc;
       index = 0;
   }
   // 返回值表示列表结束
   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); // 创建一个迭代器
   do {
      sp->f(); // 智能指针调用
      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

C++ 重載運算符和重載函數 C++重載運算符和重載函數