Nested class trouble

May 8, 2013 at 9:26pm
The trouble seems to be with my ++ operator, I'm not sure I'm doing the definition right

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
45
46
47
48
49
50
51
52
53
54
55
#include <cstdlib>

template <typename T>
class List {
	struct Node {
		T data;
		Node *next;
	} *head, *tail;
public:
	class Iterator {
		Node *ptr;
	public:
		Iterator& operator++();
	};
	List();
	~List();
	void pushEnd(T &t);
};

template <typename T>
List<T>::List() {
	head = tail = NULL;
}

template <typename T>
List<T>::~List() {
	for (Node *p = head, *pNext; p != NULL; p = pNext) {
		pNext = p->next;
		delete p;
	}
}

template <typename T>
void List<T>::pushEnd(T &t) {
	Node *newNode = new Node;
	newNode->data = t;
	newNode->next = NULL;
	if (head != NULL)
		tail->next = newNode;
	else
		head = tail = newNode;
}

template <typename T>
Iterator& List<T>::Iterator::operator++() {
	ptr = ptr->next;
	return *this;
}

int main() {
	List<int> l;
	int i = 123;
	l.pushEnd(i);
	return 0;
}
Last edited on May 9, 2013 at 8:45pm
May 9, 2013 at 8:45pm
no ideas?
May 9, 2013 at 9:14pm
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
45
46
47
48
49
50
51
52
53
#include <cstdlib>

template <typename T>
class List {
	struct Node {
		T data;
		Node *next;
	} *head, *tail;
public:
	class Iterator {
		Node *ptr;
	public:
		Iterator &operator++()
		{
            ptr = ptr->next;
            return *this;
		}
	};
	List();
	~List();
	void pushEnd(T &t);
};

template <typename T>
List<T>::List() {
	head = tail = NULL;
}

template <typename T>
List<T>::~List() {
	for (Node *p = head, *pNext; p != NULL; p = pNext) {
		pNext = p->next;
		delete p;
	}
}

template <typename T>
void List<T>::pushEnd(T &t) {
	Node *newNode = new Node;
	newNode->data = t;
	newNode->next = NULL;
	if (head != NULL)
		tail->next = newNode;
	else
		head = tail = newNode;
}

int main() {
	List<int> l;
	int i = 123;
	l.pushEnd(i);
	return 0;
}


Inlining works.
May 9, 2013 at 9:28pm
Thanks, but I imagine there must be a way to do it without inlining
May 9, 2013 at 9:38pm
No, there isn't. When you use templates, you have to inline everything, otherwise the compiler cannot properly instantiate the template.
May 9, 2013 at 9:57pm
ok, thanks
May 9, 2013 at 10:19pm
But one needn't stuff the definition of the operator in the class definition...

1
2
3
4
5
template <typename T>
typename List<T>::Iterator& List<T>::Iterator::operator++() {
	ptr = ptr->next;
	return *this;
}
Topic archived. No new replies allowed.