我不是使用模板的专家,但我不确定为什么我会得到 error: 'SLinked_List' is not a class template: friend class SLinked_List<T>;
在类的定义中SNode
。这段代码有什么问题?
谢谢你, 普拉纳夫
#include <iostream>
#include <string>
template <typename T>
class SNode{
friend class SLinked_List<T>;
private:
T data;
SNode<T>* next;
};
template <typename T>
class SLinked_List{
private:
SNode<T>* head;
public:
SLinked_List(){
head = nullptr;
}
bool empty() const { return head == nullptr; }
void insert_first (const T&);
};
template <typename T>
void SLinked_List<T> :: insert_first (const T& t){
SNode<T>* node = new SNode<T>;
node->data = t;
node->next = head;
head = node;
}
int main(){
SLinked_List<std::string> ls;
ls.insert_first("Hello");
return 0;
}
最佳答案
当您使用模板参数来引用名称时,您是在说该类型已经作为模板存在,并且我想引用该模板的特定特化。在 SNode
内部,SLinked_List
尚未声明,因此这是不允许的,因为编译器甚至不知道它是否是模板。
很明显,您希望与采用 T
的特化成为 friend ,因此您需要在 SNode
之前声明 SLinked_List
:
template <typename T>
class SLinked_List;
template <typename T>
class SNode{
friend class SLinked_List<T>;
private:
T data;
SNode<T>* next;
};
现在编译器知道 SLinked_List
是一个模板,可以这样引用。
关于templates - 如何删除错误: X is not a class template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417524/