(How to) Friend declaration of a nested iterator class towards its container class

Hi everyone!

I'm having hard times implementing a nested iterator class in a template container class which I'm making.

I'd like the iterator class to be able to access container's "first" variable, that's why I thought to declare iterator class friend of container class.

The compiler though gives me an error, which I interpreted as "Compiler is not understanding the iterator friend definition, so it cannot see container's variable".

The error is the following:
error: use of non-static data member 'first' of 'Container' from nested type 'Iterator'

Here's the accused part of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
template <class T>
class Container {
    friend class Iterator;

private:
    class Node {
        public:
            T info;
            Node*next;
            Node();
            Node(const T& x, Node* p=0): info(x), next(p) {}
            ~Node();
    };

    Node*first;
    static Node* copy(Node*);
    static void destroy(Node*);

public:
    class Iterator {
        friend class Container<T>;

    private:
        Container::Node*point;

    public:
        Iterator& operator++ ();
        Iterator operator++ (int);
    };
};

template<class T>
typename Container<T>::Iterator& Container<T>::Iterator::operator++ () {
    if(point)
        point=point->next;
    return *this;
}

template<class T>
typename Container<T>::Iterator Container<T>::Iterator::operator++ (int) {
    Iterator temp;
    temp.point = first; // <-- Here the compiler is giving me that error
    return temp;
}


If that's the problem, how should the friendship declaration of iterator towards the template container be done? (what am I missing?)

Otherwise, please, help me understand what's the mistake I made.

Thank you in advance.
Last edited on
> use of non-static data member 'first' of 'Container'
you need an object to refer to its member variables
1
2
3
4
Container a;
a.first; //accessing `first' member on `a'
first; //¿what are you talking about?
Container::first; //¿what are you talking about? 
however, I'm not saying to create an object on line 41


now, ¿why does the postfix operator do something so different to the prefix version?
it seems more a .begin() than an increase()
ne555 You are right about the postfix version.
I pasted the implementation of my begin() method under the implementation of my postfix operator and vice-versa.

This actually solved my problem and my doubts, thank you very much!

For completeness, in case someone else in the future might need the implementation of the postfix operator, here's the correct one:

1
2
3
4
5
6
7
template<class T>
typename Container<T>::Iterator Container<T>::Iterator::operator++ (int) {
    Iterator temp = *this;
    if(point)
        point = point->next;
    return temp;
}

Topic archived. No new replies allowed.