2

I'm new to the iterator class; not in how to use iterators for containers but how to implement an iterator class. I have two files, a .h and .cpp. Right now, I'm getting a compiler error in my .cpp file that displays "fatal error: 'iterator' is not a class, namespace, or enumeration". I don't understand why its telling me this.

Note: I'm sure there are other errors in my code, but right now I'm just trying to get the existing compiler error resolved.

Base.h

#ifndef Base_h
#define Base_h

class Base {
  protected: 
    std::vector<std::vector<std::string> > vec;

  public:

    class iterator {

      private:
        Base* p = nullptr;
        size_t x, y;

      public:
        iterator() = default;
        iterator(Base *, size_t, size_t);
        ~iterator();
        iterator &operator++();
        Base operator*() const;
    }     

    iterator begin() const;
    iterator end() const;
    // bunch of other iterator::functions and Base::functions
};

#endif

Base.cpp

iterator::iterator(Base *b, size_t i, size_t j): p(b), x(i), y(j) {}
iterator::~iterator();
// Bunch of other iterator::functions including Base::functions

Compiler Error

Base.cc:254:13: fatal error: 'iterator is not a class, namespace, or enumeration
iterator::iterator(Base *b, size_t i, size_t j): p(b), x(i), y(j) {}
^

/Library/Developer/CommandLineTools/usr/include/c++/v1/iterator:522:29: note: 'iterator' declared here
struct _LIBCPP_TEMPLATE_VIS iterator
  • 2
    `iterator` is a nested class: try qualifiying the implementation in cpp file with `Base::iterator::iterator` Or try avoid to declare iterator as nested class – Gian Paolo Nov 19 '18 at 23:31
  • I believe that worked. Although, it came up with another compiler error but one I can deal with. Thanks. If all else fails, I may avoid a nested class. Thanks. – N. Colostate Nov 19 '18 at 23:36
  • 1
    well, as a start, why do you need a nested class? (actually, I just asked this myself) see also https://stackoverflow.com/questions/4571355/why-would-one-use-nested-classes-in-c – Gian Paolo Nov 19 '18 at 23:40
  • I decided on using a nested class through examples provided from various .edu addresses. So, I assume it was standard practice. From the comments so far, it doesn't seem that way. – N. Colostate Nov 19 '18 at 23:44
  • the following declaration `Base operator*() const;` seems suspicious. You really want to return a copy of `Base`? – Phil1970 Nov 20 '18 at 02:01

0 Answers0