Перегрузка оператора приращения для класса итератора

Я пытался перегрузить оператор ++ для перемещения итератора по списку, но продолжаю получать ошибку C2460 «List :: Iterator :: ++»: использует «List :: Iterator»

template <typename E>
class List : public SLinkedList<E> {

public:
// NOTE THE DIFFERENT LETTER – IT IS ONLY USED HERE! 
// Use E everywhere else! m
// For a nested class, methods are declared and defined *INSIDE*
// the class declaration.
template <typename I>
class Iterator {
public:
    // Give List access to Iterator private fields.
    friend class List<E>;

    // These are the minimum methods needed.
    E operator* {nodePosition->elem}; //dereference the iterator and return a value
    Iterator<E> operator++ {nodePosition = nodePosition->next};  //increment the iterator
    Iterator<E> operator-- {
        nodePosition = nodePosition->prev;
    }  //decrement the iterator
    bool operator==(const Iterator<E> p)  { 
        return (nodePosition == p)
    }  //test equality of iterators
    bool operator!=(const Iterator<E> p) {
        return (nodePosition != p)
    }   //test inequality of iterators


private:
    // Constructors & destructor here since only want List class to access.

    // List constructor called from List::begin(). Use initializer list or
    // create class copy constructor and assignment overload.
    Iterator(const List<E>* sl) : llist(sl) {
        nodePosition = sl->head;
    }

    // Class fields.
    const List<E>* llist;     //give Iterator class a handle to the list
    Node<E>* nodePosition;  //abstracted position is a pointer to a node

}; /** end Iterator class **/

   /* The Iterator class is now fully defined. The rest of these
   statements must go AFTER the Iterator class or the compiler
   won’t have complete information about their data types.
   */

   // REQUIRED: While not necessary for the code to work, my test suite needs
   // this defined. Create a less cumbersome name for Iterator<E>. Use 
   // anywhere you would have used List<E>::Iterator<E> in class List. Allows 
   // this syntax in main() -- List<int>::iterator instead of List<int>::Iterator<int>.
typedef typename List<E>::Iterator<E> iterator;

/***    All method declarations and fields for the List class go here.
Any method that returns an iterator must be defined here.
***/
iterator begin() const {  //return an iterator of beginning of list
                          // Call iterator constructor with pointer to List that begin() was 
                          // called with.
    return iterator(this);
}
E back();
E pop_back();
void push_back(const E e);

}; / ** объявление класса end List ** /


person Richard Rasmussen    schedule 03.12.2015    source источник
comment
В ваших operator++, operator-- и operator* отсутствует оператор возврата. и отсутствует список параметров. Все они тоже имеют неправильный тип возврата   -  person M.M    schedule 04.12.2015
comment
Если я включаю оператор return, я получаю синтаксическую ошибку: return. Я изменил возвращаемый тип на Iterator ‹E› &   -  person Richard Rasmussen    schedule 04.12.2015
comment
Вы тоже везде пропускаете / добавляете точки с запятой. Они нужны вашим операторам возврата, а вашим методам не нужен конечный (т.е. { ... };)   -  person Michael Oliver    schedule 04.12.2015
comment
Вам нужен оператор возврата, и исправьте ваши синтаксические ошибки.   -  person M.M    schedule 04.12.2015


Ответы (1)


Следующие определения методов имеют неправильный формат:

E operator* {nodePosition->elem}; //dereference the iterator and return a value
Iterator<E> operator++ {nodePosition = nodePosition->next};  //increment the iterator
Iterator<E> operator-- {
    nodePosition = nodePosition->prev;
}  //decrement the iterator

Несмотря на то, что ни один из этих методов не требует параметров, () по-прежнему требуется. Компилятор, вероятно, видит в них какие-то определения переменных и позволяет этому продолжаться достаточно долго, чтобы получить сообщение об ошибке, о котором сообщает OP.

E operator*() {nodePosition->elem}; //dereference the iterator and return a value
Iterator<E> operator++() {nodePosition = nodePosition->next};  //increment the iterator
Iterator<E> operator--() {
    nodePosition = nodePosition->prev;
}  //decrement the iterator

Все они также заявляют, что возвращают значение, но ни одно из тел функций не возвращает. Прежде чем этот код заработает, требуется еще много работы.

person user4581301    schedule 04.12.2015