Search code examples
c++operator-overloadingoperatorsmingw-w64

Operator overloading, definition/header for all operators


How best to split the following iterator code into a header and definition.

// std::iterator example
#include <iostream>     // std::cout
#include <iterator>     // std::iterator, std::input_iterator_tag

class MyIterator : public std::iterator<std::input_iterator_tag, int>
{
  int* p;
public:
  MyIterator(int* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) const {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) const {return p!=rhs.p;}
  int& operator*() {return *p;}
};

int main () {
  int numbers[]={10,20,30,40,50};
  MyIterator from(numbers);
  MyIterator until(numbers+5);
  for (MyIterator it=from; it!=until; it++)
    std::cout << *it << ' ';
  std::cout << '\n';

  return 0;
}

from: http://www.cplusplus.com/reference/iterator/iterator/

How would you implement the other operators in this context?

This example also shows that you pass an array into the iterator but would this same approach be used if you wanted to be able to itterate through some property(s) or data that your class instance has?

Would you create a seperate iterator that works with your class or implement the operator methods inside the class itself?


Solution

  • About splitting into implementation and definition I would do it like this

    MyIterator.h file :

    #IFNDEF MYITERATOR_H
    #DEFINE MYITERATOR_H
    #include <iterator>
    class MyIterator : public std::iterator<std::input_iterator_tag, int>
    {
     private:
       int* p;
     public:
        MyIterator(int *);
        MyIterator(const MyIterator&);
        MyIterator& operator++();
        MyIterator operator++(int);
        bool operator==(const MyIterator&);
        bool operator!=(const MyIterator&);
        int& operator*();
    };
    
    #ENDIF 
    

    MyIterator.cpp file:

    #include "MyIterator.h"
    
    MyIterator::MyIterator(int * x){
        p = x;
    }
    MyIterator::MyIterator(const MyIterator& mit){
        p = mit.p;
    }
    MyIterator& MyIterator::operator++(){
        ++p;
        return *this;
    }
    MyIterator MyIterator::operator++(int x){
        MyIterator temp(*this);
        ++p;
        return temp;
    }
    bool MyIterator::operator==(const MyIterator& rhs){
        return p == rhs.p;
    }
    bool MyIterator::operator!=(const MyIterator& rhs){
        return p != rhs.p;
    }
    int& operator*(){
        return *p;
    }
    

    you just need to add #include "MyIterator.h" to your main program to be able to use it