// 這是 Node.h 檔案
#ifndef NODE
#define NODE
template <typename T>
class Node
{
private:
T elem;
Node *next;
friend class LinkedList<T>;
};
#endif // NODE
這是 LinkedLilst.h 檔案
#ifndef LINKED_LIST
#define LINKED_LIST
#include "Node.h"
template <typename T>
class LinkedList
{
public:
LinkedList();
~LinkedList();
bool empty() const;
const T &front() const;
void addFront(const T &e);
void removeFront();
private:
Node<T> *head;
};
#endif // LINKED_LIST
這是 LinkedList.cpp 檔案
#include <iostream>
#include "LinkedList.h"
using namespace std;
template <typename T>
LinkedList<T>::LinkedList() : head(NULL) {}
template <typename T>
bool LinkedList<T>::empty() const // I don't want it to modify the data member of the function.
{
return head == NULL;
}
template <typename T>
LinkedList<T>::~LinkedList()
{
while (!empty())
removeFront();
}
...
...
...
這是我的 main.cpp 檔案
#include <iostream>
#include "LinkedList.h"
using namespace std;
int main()
{
LinkedList<int> ls;
ls.addFront(3);
cout << ls.front();
return 0;
}
我不知道為什么會收到錯誤訊息:“LinkedList”不是類模板
friend class LinkedList<T>; in Node.h
問題是 Node.h 檔案沒有任何與 LinkedList 相關的內容。我添加了 LinkedList Declaration 但它仍然顯示錯誤。請幫忙。
uj5u.com熱心網友回復:
您需要轉發宣告LinkedList類模板:
#ifndef NODE
#define NODE
template<class> class LinkedList; // <- forward declaration
template <typename T>
class Node
{
private:
T elem;
Node *next;
friend class LinkedList<T>;
};
#endif // NODE
您將遇到的下一個問題可能是鏈接問題。我建議將類成員函式定義移動到頭檔案中。更多關于這里:為什么模板只能在頭檔案中實作?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311147.html
上一篇:C#:“'System.Collections.Generic.Dictionary<object,object>.KeyCollection'不包含'ToL
下一篇:如何動態地將型別別傳遞給泛型類
