我不是程序员,但实际上是一名律师,他花了大约一年时间学习C ++。我这样做是为了一个爱好。无论如何,我已经开始尝试使用模板,但却无法弄清楚如何做到这一点。我正在使用Node Struct实现一个模板化的队列,我也在队列类之外进行模板化和声明。如何将队列的模板化类型传递给Node结构?任何其他评论一般表示赞赏。谢谢。 示例代码:
template<class T> struct Node{
Node<T> *next; T data;
Node<T> * previous;
Node (T d) {data = d;}
};
template<class Q> class Queue
{
int count;
Node<Q> *head; -> doesn't work -'Node<T>::data uses undefined class Q.
Node<Q> *tail;
public:
Queue() : count(0), head(NULL), tail(NULL) {}
~Queue();
void Enqueue(Q data);
Node<Q>* Dequeue();
std::ostream& Print(std::ostream& os) const;
};
void Queue<class Q>::Enqueue(Q data)
{
Node<Q> * newNode = new Node<Q>(data);
if(!head)
head = tail = newNode;
else
{
tail->next = newNode;
tail = newNode;
tail->next=NULL;
}
++count;
}
Queue<class Q>::~Queue()
{
while(head)
{
Node<Q> * tmp = head;
head=head->next;
delete tmp;
}
}
Node<Q> * Queue<class Q>::Dequeue()
{
if(!head) return NULL;
Node<Q> * temp = head;
head = head->next;
--count;
return temp;
}
std::ostream& Queue<class Q>::Print(std::ostream& os) const
{
if(!head)
{
os<<"Empty list"<<endl;
return os;
}
for(Node<Q> *itr = head; itr!=NULL; itr=itr->next)
os<<" "<<itr->data <<" "<<endl;
return os;
}
std::ostream& operator<<(std::ostream& os, const Queue<Q>& q)
{
return q.Print(os);
}
答案 0 :(得分:1)
template<typename T> struct Node{
Node<T> *next; T data;
Node<T> * previous;
Node (T d) {data = d;}
};
template<typename Q> class Queue
{
int count;
Node<Q> *head;
Node<Q> *tail;
public:
Queue() : count(0), head(NULL), tail(NULL) {}
~Queue();
void Enqueue(Q data);
Node<Q>* Dequeue();
std::ostream& Print(std::ostream& os) const;
};
template<typename Q>
void Queue<Q>::Enqueue(Q data)
{
Node<Q> * newNode = new Node<Q>(data);
if(!head)
head = tail = newNode;
else
{
tail->next = newNode;
tail = newNode;
tail->next=NULL;
}
++count;
}
template<typename Q>
Queue<Q>::~Queue()
{
while(head)
{
Node<Q> * tmp = head;
head=head->next;
delete tmp;
}
}
template<typename Q>
Node<Q> * Queue<Q>::Dequeue()
{
if(!head) return NULL;
Node<Q> * temp = head;
head = head->next;
--count;
return temp;
}
template<typename Q>
std::ostream& Queue<Q>::Print(std::ostream& os) const
{
if(!head)
{
os<<"Empty list"<<endl;
return os;
}
for(Node<Q> *itr = head; itr!=NULL; itr=itr->next)
os<<" "<<itr->data <<" "<<endl;
return os;
}
template<typename Q>
std::ostream& operator<<(std::ostream& os, const Queue<Q>& q)
{
return q.Print(os);
}
我为你修复了编译错误。