English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C++ Surcharge d'opérateurs et surcharge de fonctions
opérateur d'accès aux membres de la classe ( -> ) Peut être surchargé, mais c'est assez compliqué. Il est défini pour donner à une classe un comportement de "pointeur". -> Doit être une fonction membre. Si vous utilisez -> L'opérateur doit retourner un pointeur ou un objet de classe.
opérateur -> Généralement avec l'opérateur de référence de pointeur * L'utilisation combinée est utilisée pour réaliser la fonction de "pointeur intelligent". Ces pointeurs sont des objets whose behavior is similar 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 suffix 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 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 the standard methods of the vector } friend class SmartPointer; }; // Implement smart pointer to access 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) // suffixed version { return operator++(); } // Surcharge d'opérateurs -> 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); // Création d'un itérateur do { sp->f(); // Appel de pointeur intelligent sp->g(); } while(sp++); return 0; }
Lorsque le code suivant est compilé et exécuté, il produit les résultats suivants :
10 12 11 13 12 14 13 15 14 16 15 17 16 18 17 19 18 20 19 21