Latest web development tutorials

C ++ class member access operator -> reload

C ++ function overloading and operator overloading C ++ function overloading and operator overloading

Class member access operator (->) can be overloaded, but it is cumbersome. It is defined for a given class "pointer" behavior. Operator -> must be a member function. If you use the -> operator, the return type must be a pointer or a class of objects.

Operator -> is usually a pointer dereference operator * used in combination with, for achieving "smart pointer" function. These pointers are pointers behave like normal objects, the only difference is that when you pass a pointer to access the object, they perform other tasks. For example, when the pointer is destroyed, or when a pointer to another object, the object will be automatically deleted.

Indirect reference operator -> it can be defined as a unary postfix operator. That is, a given class:

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

Ptr class of objects can be used to access a member of class X,use the pointer usage is very similar. E.g:

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

Statement p-> m is interpreted as (p.operator -> ()) -> m. Similarly, the following example shows how to reload a class member access operator ->.

#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;
}

When the above code is compiled and executed, it produces the following results:

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

C ++ function overloading and operator overloading C ++ function overloading and operator overloading