gpt4 book ai didi

c++ - 基本模板链表

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:29:55 26 4
gpt4 key购买 nike

#include <iostream>
#include <string>

using namespace std;

template <class T>
class Node{
friend class LinkedList<T>;
private:
T data;
Node <T> *next;
public:
Node();
Node(T d);
~Node();
};

template <class T>
Node<T>::Node(){
T data = 0;
next = 0;
}

template <class T>
Node<T>::Node(T d){
data = d;
next = 0;

}

template<class T>
Node<T>::~Node(){
delete next;
}

template <class T>
class LinkedList{
private:
Node <T> *head;
public:
LinkedList();
~LinkedList();
void Push_Front(const T& e);
}

template<class T>
LinkedList <T>::LinkedList(){
head = 0;
}

template <class T>
LinkedList<T>::~LinkedList(){
delete head;
}

template <class T>
void LinkedList<T>::Push_Front(const T &e){
Node<T> *newNode = new Node<T>(e);

if(head == 0)
head = new Node<T>(e);

newNode->next = head;
head = newNode;
}


void main(){
LinkedList<int> list;

list.Push_Front(10);


int t;
cin>>t;
return ;
}

我正在尝试编写链表的模板版本。我遇到了一些错误,不确定为什么。当我尝试创建 friend 类 LinkedList 时发生错误,我需要这样做以便我可以从 LinkedList 访问 T 数据。

: error C2059: syntax error : '<'
: see reference to class template instantiation 'Node<T>' being compiled
: error C2238: unexpected token(s) preceding ';'
: error C2143: syntax error : missing ';' before 'template'
: error C2989: 'LinkedList' : class template has already been declared as a non-class template
: see declaration of 'LinkedList'
: 'LinkedList': multiple template parameter lists are not allowed
: error C2988: unrecognizable template declaration/definition
: error C2059: syntax error : '<'
: error C2588: '::~LinkedList' : illegal global destructor
: fatal error C1903: unable to recover from previous error(s); stopping compilatio

最佳答案

LinkedList 的类定义末尾缺少分号.然而,即使你修复了它,因为 Node<T>需要了解 LinkedList<T>反之亦然,您需要在顶部声明它们:

#include <iostream>
#include <string>

using namespace std;

template <typename T> class Node;
template <typename T> class LinkedList;

//Code as before

关于c++ - 基本模板链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13577324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com