C + + programming ideas, Volume 1, Chapter 12 operator overloading operators not commonly used operator->

When you want an object to behave like a pointer, you usually use operator - >

Pointer indirect reference operator must be a member function

The pointer indirect reference operator has a limitation: it must return an object that also has a pointer indirect
Reference operator, or must return a pointer, used to select a pointer indirect reference operator arrow
What to point to

 

//: C12:SmartPointer.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
#include <iostream>
#include <vector>
#include "../require.h"
using namespace std;

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 = 47;
int Obj::j = 11;

// Container:
class ObjContainer {
  vector<Obj*> a;
public:
  void add(Obj* obj) { a.push_back(obj); }
  friend class SmartPointer;
};

class SmartPointer {
  ObjContainer& oc;
  int index;
public:
  SmartPointer(ObjContainer& objc) : oc(objc) {
    index = 0;
  }
  // Return value indicates end of list:
  bool operator++() { // Prefix
    if(index >= oc.a.size()) return false;
    if(oc.a[++index] == 0) return false;
    return true;
  }
  bool operator++(int) { // Postfix
    return operator++(); // Use prefix version
  }
  Obj* operator->() const {
    require(oc.a[index] != 0, "Zero value "
      "returned by SmartPointer::operator->()");
    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]); // Fill it up
  SmartPointer sp(oc); // Create an iterator
  do {
    sp->f(); // Pointer dereference operator call
    sp->g();
  } while(sp++);
  getchar();
} ///:~

 

Class Obj defines some objects used in the program

In main(), once the Obj object is loaded into the container oc, the SP of a SmartPointer class is created

The underlying mechanism of pointer indirect operators is more complex than other operators, but the purpose is the same. It is a class
More convenient syntax for

output
47
11
48
12
49
13
50
14
51
15
52
16
53
17
54
18
55
19
56
20

Program exception after

Added by fordyh on Fri, 31 Jan 2020 12:32:17 +0200