[英]template class c++
我嘗試為我的大學項目設計一個模板。 我寫了以下代碼:
#ifndef _LinkedList_H_
#define _LinkedList_H_
#include "Link.h"
#include <ostream>
template <class L>//error one
class LinkedList
{
private:
Link<L> *pm_head;
Link<L> * pm_tail;
int m_numOfElements;
Link<L>* FindLink(L * dataToFind);
public:
LinkedList();
~LinkedList();
int GetNumOfElements(){return m_numOfElements;}
bool Add( L * data);
L *FindData(L * data);
template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two
L* GetDataOnTop();
bool RemoveFromHead();
L* Remove(L * toRemove);
這個模板使用鏈接類templete
#ifndef _Link_H_
#define _Link_H_
template <class T>//error 3
class Link
{
private:
T* m_data;
Link* m_next;
Link* m_prev;
public:
Link(T* data);
~Link(void);
bool Link::operator ==(const Link& other)const;
/*getters*/
Link* GetNext()const {return m_next;}
Link* GetPrev()const {return m_prev;}
T* GetData()const {return m_data;}
//setters
void SetNext(Link* next) {m_next = next;}
void SetPrev(Link* prev) {m_prev = prev;}
void SetData(T* data) {m_data = data;}
};
error one: shadows template parm `class L'
error two:declaration of `class L'
error three: shadows template parm `class T'
我不明白這是什么問題。 我真的可以用你的幫助謝謝:)
這些錯誤消息確實屬於一起:
a.cc:41: error: declaration of ‘class L’
a.cc:26: error: shadows template parm ‘class L’
這意味着在第41行中,您引入了模板參數L; 在我的副本中,這指的是
template <class L> friend ostream & operator<<(ostream& os,
const LinkedList<L> listToprint);//error two
該聲明會影響第26行中的模板參數:
template <class L>//error one
class LinkedList
您需要在friend聲明中重命名模板參數。
編輯 :相關語言規范是14.6.1 / 7
模板參數不得在其范圍內重新聲明(包括嵌套范圍)。 模板參數的名稱不能與模板名稱相同。
當你在const LinkedList<L> listToprint
引用L
時,不清楚你是指朋友的L還是班級的L。 所以寫
template <class L1> friend ostream & operator<<(ostream& os,
const LinkedList<L1> listToprint);
只需刪除
template <class L>
來自friend
會員功能聲明。
您還需要使用std::ostream
替換ostream
使用,除非您在代碼中的某處using namespace std
。
否則,代碼看起來很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.