I'm doing a linked list class that holds instances of 7 or 8 classes that I've written. I want to be able to access these classes methods. list->item.methodname(); ... is there anyway to do this without declaring my item field public?
1 #ifndef LIST_H
2 #define LIST_H
3 #include <iostream.h>
4 #include "/home/mud/classes/object/object.cpp"
5
6 template<class T>
7 class List;
8
9 template<class T>
10 class Node
11 {
12 friend List<T>;
13 public:
14 // This is declared public because we need to access functions
15 // of the item from outside functions and classes. I wish I
16 // knew of a better way to do this.
17 T item; // This will hold an object of type T
18 private:
19 Node *next;
20 };
21
22 template<class T>
23 class List
24 {
25 public:
26 List(); // Constructor
27 ~List(); // Destructor
28
29 void add(int new_item); // Add an item to the end of the list
30 void kill(int x); // Delete the specified item
31 void seek(int x); // Set the current pointer to the specified item
32 void print(); // Print the descriptions of all the items
33 // This is only for testing
34
35 Node<T>* current; // Current item pointer
36
37 private:
38 Node<T>* head;
39 Node<T>* tail;
40
41 };
42
43
44 #endif // LIST_H
private:
T item;
public:
T& GetItem() { return item; }
const T& GetItem() const { return item; }
Try to never expose a member variable, always use access functions.
Other suggestions:
List<T>::add() should take const T& not int
current should be made private and a GetItem function should be added to List
T& GetItem() { return current->GetItem(); }
There is no reason for clients of list to know about Nodes. This way you have the flexibility to change the way you implement list.