0
votes

I can't understand why my code doesn't compile.

template<class Priority,class T> class PriorityQueue {
public:
  class Iterator;
  //some methods
  Iterator begin() const;
  Iterator end() const;
};

and then in the Iterator class:

template<class Priority,class T>
class PriorityQueue<Priority,T>::Iterator {
   //implement ctor,operator++,==etc.

Almost all the 84-errors I get are about these functions:

template<class Priority,class T>
Iterator<Priority,T> PriorityQueue<Priority,T>::begin() const{
    return Iterator<Priority,T>(firstNode);
}
template<class Priority,class T>
Iterator<Priority,T> PriorityQueue<Priority,T>::end() const{
    return Iterator<Priority,T>(nullptr);
}

The error is: Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int. And: Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int and: Error 1 error C2143: syntax error : missing ';' before '<'. All regarding the method begin() and end() (in their first line Iterator PriorityQueue::begin()). EDIT: I tried using typename but it didn't help.

1
class Iterator; is a forward declaration you can't declare classes and then define them. - 101010
Could you tell me what is the right way of doing this? - user3748682
Easiest way is just putting the definition of Iterator (i.e. class Iterator { ... };) where you currently have the declaration (inside PriorityQueue). - Tony Delroy
I copied all class Iterator inside PQ, but now that all class Iterator is public, anyone can use its ctor right? isn't that a bad thing? - user3748682
Post your full code (stripped down to a minimal example that reproduces the problem). As it is, any answers will be based on guessing about the exact form of your code and the problems that it could contain. - Mankarse

1 Answers

1
votes

You can do something like below:

template<class Priority, class T> class PriorityQueue {
  class Iterator {
    //implement ctor,operator++,==etc.
  };

public:
  typedef Iterator iterator;
  //some methods//implement ctor,operator++,==etc.
  Iterator begin() const;
  Iterator end() const;
};

template<class Priority,class T>
typename PriorityQueue<Priority, T>::iterator 
PriorityQueue<Priority,T>::begin() const    {
    return Iterator(); // return right staff
}

template<class Priority,class T>
typename PriorityQueue<Priority, T>::iterator
PriorityQueue<Priority,T>::end() const{
    return Iterator(); // return right staff
}
  • I recommend you declare/define your Iterator private, and provide access via a typedef, much like what STL does.

DEMO