我新加入 C++ 模板。 编辑时出错 :
main.cpp(17) : error C2923: Iterator :
myWords is not a valid template type argument for parameter T
main.cpp(17) : error C2133: iterator : unknown size error C2512:
Iterator : no appropriate default constructor available
Code:
#include "MyList.h"
#include "MyList.cpp"
#include <string>
using namespace std;
int main()
{
LinkedList<string> myWords;
myWords.addAtBeginning("Data");
Iterator<myWords> iterator;
//iterator.advance();
return 0;
}
页眉文件
#ifndef MYLIST_H
#define MYLIST_H
template <class T>
class Iterator;
template <class T>
struct link
{
link * previous;
link * next;
T s;
};
template <class T>
class LinkedList
{
link<T> * head; // No longer a global variable
public:
void addAtBeginning(T word);
void printAll();
void printString(link<T> *p); // prints the string in the link pointed to by p.
void deleteFromBeginning(); // deletes the first link in the list.
LinkedList(); // default constructor
friend class Iterator<T>;
};
template <class T>
class Iterator
{
private:
link<T> * p;
public:
// construct the iterator by having it refer to a linked list
Iterator(LinkedList<T> whatIamIterating);
// returns the string in the current link
T current();
// move the Iterator to the next link
void advance();
// returns true when we are finished with list
int atEnd();
};
#endif
CPP 档案资料
#include "MyList.h"
// Default constructor of linkedlist
template <class T>
LinkedList<T>::LinkedList()
{
head=0;
}
// Function to add at the beginning
template <class T>
void LinkedList<T>::addAtBeginning(T word)
{
link<T> * tmp;
tmp = new link<T>;
tmp->s = word;
tmp->next=head;
tmp->previous=0;
head=tmp;
}
// Function to print the all strings
template <class T>
void LinkedList<T>::printAll()
{
link<T> * tmp;
tmp = head;
while (tmp != 0)
{
cout << tmp->s;
tmp = tmp->next;
}
cout << endl;
}
// Prints the string in the link pointed to by p.
template <class T>
void LinkedList<T>::printString(link<T> *p)
{
cout << p->s << endl;
}
// Deletes the first link in the list.
template <class T>
void LinkedList<T>::deleteFromBeginning()
{
link<T> *oldhead = head;
head = head->next;
delete oldhead;
}
// Function definitions for Iterator class
// Constructor for iterator class
template <class T>
Iterator <T>::Iterator(LinkedList<T> whatIamIterating)
{
p = whatIamIterating.head;
}
// Function to get the current string of the node
template <class T>
T Iterator<T>::current()
{
return p->s;
}
template <class T>
void Iterator<T>::advance()
{
p = p->next;
}
template <class T>
int Iterator<T>::atEnd()
{
if (p == 0)
return 1;
else
return 0;
}