首先C++的模板不支持分离编译模型。如果不是模板, 那么实现文件和接口文件分开会是一个good practice in C++。 但是对于模板, 我们必须要将实现文件 和 头文件放在一起。 否则会发生undefined refernce to .....
例如下例中, 我们修改为如下, 一旦将实现文件和头文件分开, 会错的很难看的。
具体的, 各个文件如下:
LinkedListNode.h 文件如下:
#ifndef LINKED_LIST_NODE_H
#define LINKED_LIST_NODE_H
//definition of the node
template <class Type>
struct nodeType {
Type info;
nodeType<Type>* link;
};
#endif
LinkedListIterator.h:
#ifndef LINKED_ITERATOR
#define LINKED_ITERATOR
//This class specifies the members to implement an iterator
#include "LinkedListNode.h"
template <class Type>
class linkedListIterator {
public:
linkedListIterator();
//default constructor
//postcondition: current = NULL;
linkedListIterator(nodeType<Type>* ptr);
//constructors with a parameter
//postcondition: current = ptr;
Type operator*();
//function to overload the dereferencing operator *
//postcondition: returns the info contained in the node.
linkedListIterator<Type> operator++();
//overload the preincrement operator
//postcondition: the iterator is advanced to the next node.
bool operator==(const linkedListIterator<Type>& right) const;
//overload the equality operator
//postcondition: returns true if the iterator is equal to the
//iterator specifies by right, otherwise it returns false.
bool operator!=(const linkedListIterator<Type>& right) const;
// overload the not equal to operator.
//postcondition: returns true if this iterator is not equal
//to the iterator specifies by right, otherwise it returns false.
private:
nodeType<Type>* current; //pointer to point to the current node in the linked list
};
template <class Type>
linkedListIterator<Type>::linkedListIterator() {
current = NULL;
}
template <class Type>
linkedListIterator<Type>::linkedListIterator(nodeType<Type>* ptr) {
current = ptr;
}
template <class Type>
Type linkedListIterator<Type>::operator*() {
return current -> info;
}
template <class Type>
linkedListIterator<Type> linkedListIterator<Type>::operator++() {
current = current -> link;
return *this;
}
template <class Type>
bool linkedListIterator<Type>::operator==(const linkedListIterator<Type>& right) const {
return (right == right.current);
}
template <class Type>
bool linkedListIterator<Type>::operator!=(const linkedListIterator<Type> &right) const {
return (current != right.current);
}
#endif
LinkedListType.h:
#ifndef LINKED_TYPE_H
#define LINKED_TYPE_H
//this class specifies members to implement the basic properties
//of a linked list. This is an abstract class. We cannot instantiate
//an object of this class
#include "linkedListIterator.h"
#include "LinkedListNo