Cplusplus-class-member-access-operator-overloading

提供:Dev Guides
移動先:案内検索

クラスメンバーアクセス演算子(→)C ++でのオーバーロード

クラスメンバーアクセス演算子(→)はオーバーロードできますが、少し注意が必要です。 クラス型に「ポインタのような」動作を与えるように定義されています。 演算子→はメンバー関数でなければなりません。 使用する場合、戻り値の型はポインターまたは適用可能なクラスのオブジェクトでなければなりません。

operator→は、「スマートポインター」を実装するために、ポインター参照解除演算子*と組み合わせてよく使用されます。これらのポインターは、通常のポインターのように動作するオブジェクトです。ただし、ポインターが破棄されるか、ポインターが別のオブジェクトを指すために使用される場合のオブジェクトの自動削除など、オブジェクトにアクセスすると他のタスクを実行します。

間接参照演算子→は、単項後置演算子として定義できます。 つまり、クラスが与えられた-

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