【发布时间】:2019-09-27 22:53:15
【问题描述】:
我被分配将我的链表类转换为模板,但我遇到了一些困惑。我需要将其作为单个 .h 文件提交。
当我尝试构建时,每次提到LLnode、fwdPtr 和theData 都会出错。那是结构的每一个元素,所以我在那里做了一些非常错误的事情。此外,struct 定义本身标有syntax error
template <class V>
class LL
{
private:
LLnode * header;
struct <V> LLnode;
{
LLnode * fwdPtr; // has a pointer member
V theData; // the data within the node
};
public:
LL()
{
header = nullptr;
}
void push_front(string data)
{
LLnode * new_node;
new_node = new LLnode;
new_node -> theData = data;
if (header == nullptr)
{
header = new_node;
new_node -> fwdPtr = nullptr;
}
else
{
LLnode * temp;
temp = header;
header = new_node;
new_node -> fwdPtr = temp;
}
return;
}
.... more functions below ....
在测试函数的main() 中,将实例化一个新的链表,并将<string> 强制转换为类型。这就是我将struct LLnode 移动到class LL 的private 成员部分的原因。这也是我在整个结构中使用V 的原因。因为该演员需要深入到结构本身,所以当我为节点动态分配内存时,它会知道接受string 数据
我知道我需要更改函数定义以包含 V 并在整个过程中使用 V 和一些变量。但我不明白在哪里以及为什么。我对模板类如何与指针和程序员定义的结构相关感到困惑。我了解教科书中模板类/函数的简单示例,但我在这里迷路了。
提前感谢您的帮助!
编辑:这是我收到的错误消息(按要求)
../LL_template_class.h:23:3: error: unknown type name 'LLnode'
LLnode * header;
^
../LL_template_class.h:24:3: error: declaration of anonymous struct must be a definition
struct <V> LLnode;
^
../LL_template_class.h:24:3: warning: declaration does not declare anything [-Wmissing-declarations]
../LL_template_class.h:25:3: error: expected member name or ';' after declaration specifiers
{
^
../LL_template_class.h:37:4: error: unknown type name 'LLnode'
LLnode * new_node;
^
../LL_template_class.h:38:19: error: unknown type name 'LLnode'
new_node = new LLnode;
^
../LL_template_class.h:48:5: error: unknown type name 'LLnode'
LLnode * temp;
但就像我说的,我在所有提及我的 struc LLnode 元素时都会收到 can not resolve 错误
【问题讨论】:
-
您能提供您收到的错误信息吗?
-
当您编写
template <class V> class LL { ... };时,编译器基本上会为LL创建一个“千篇一律”的模板。然后,当您实例化LL<int>时,它会标记出一个名为LL<int>的{ ... };内容的新实例(对于其他类型类似)。所以你的struct <V> LLnode; { ... };没有意义,因为如果LL不是 模板,你只需写struct LLnode { ... };,它就会按你的预期工作。我发现从具体类型而不是模板开始(LLInt而不是LL<T>)通常很有用,然后再返回模板化。 -
要充分利用 Stackoverflow - 首先提供minimal reproducible example。想帮忙的人会增加很多。
-
非常感谢@Justin 和@Ted。以后我会尽量精简我的问题。它可能会帮助我弄清楚问题的核心是什么,并让我得到更多的回应
标签: c++ class templates struct