我是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
代码:
#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;
}
答案 0 :(得分:2)
需要Iterator< LinkedList<string> >
。 类型名称是模板参数,而不是对象。
答案 1 :(得分:0)
在
Iterator<myWords> iterator;
您使用myWords
作为类型,但它是一个变量。你想要
Iterator<string> iterator(myWords);
由于string
是您用于LinkedList
的类型(解决第一个编译器错误),Iterator
cosntrcutor会使用LinkedList<T>
个对象(在您的情况下T
为string
)(解决第二个编译器错误)