English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C++ Operator Overloading and Overloaded Functions
class member access operator ( -> )Can be overloaded, but it is麻烦。It is defined to give a class the behavior of a "pointer". Operator -> Must be a member function. If used -> The operator must return a pointer or an object of the class.
operator -> Usually with the pointer reference operator * Combined use is used to implement the function of "smart pointer". These pointers are objects that behave similarly to normal pointers, the only difference being that when you access an object through a pointer, they perform other tasks. For example, when a pointer is destroyed, or when a pointer points to another object, the object is automatically deleted.
indirect reference operator -> can be defined as a unary postfix operator. That is, given a class:
class Ptr{ //... X * operator->(); };
class Ptr objects can be used to access the class X members, the usage is very similar to that of pointers. For example:
void f(Ptr p) { p->m = 10 ; // (p.operator->())->m = 10 }
statement p->m is interpreted as (p.operator->())->m. Similarly, the following example demonstrates how to overload the class member access operator ->。
#include <iostream> #include <vector> using namespace std; // Assume an actual class class Obj { static int i, j; public: void f() const { cout << i++ << endl;} void g() const { cout << j++ << endl;} }; // Static member definition 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 the standard methods of the vector } friend class SmartPointer; }; // Implement smart pointer for accessing the members of class Obj class SmartPointer { ObjContainer oc; int index; public: SmartPointer(ObjContainer& objc) { oc = objc; index = 0; } // The return value indicates the end of the list bool operator++() // prefix version { if(index >= oc.a.size()) - 1) return false; if(oc.a[++index] == 0) return false; return true; } bool operator++(int) // suffix version { return operator++(); } // Operator Overloading -> 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; }
When the above code is compiled and executed, it will produce the following results:
10 12 11 13 12 14 13 15 14 16 15 17 16 18 17 19 18 20 19 21