C++ 无法编译和定位错误
我正在尝试编写一个代码来查找链接列表中循环的开头。 这是我的密码:C++ 无法编译和定位错误,c++,C++,我正在尝试编写一个代码来查找链接列表中循环的开头。 这是我的密码: #include <iostream> template <class T> class LinkedList { public: struct node { T data; node* next; }; node* head; LinkedList() : head(NULL){}; void AppendToTail(T
#include <iostream>
template <class T>
class LinkedList
{
public:
struct node
{
T data;
node* next;
};
node* head;
LinkedList() : head(NULL){};
void AppendToTail(T data);
void InsertToHead(T data);
void RemoveDuplicates();
void PrintList();
T lastNthNode(int N);
bool operator==(const LinkedList<T>& L);
node* FindBeginningNodeLoop();
};
template <class T>
node* LinkedList<T>::FindBeginningNodeLoop()
{
if (head == NULL)
return NULL;
node* slow = head;
node* fast = head;
while (fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
break;
}
if (fast == NULL)
return NULL;
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
编译器给出以下错误:
1> main.cpp
1> c:\users…\linkedlist.h177:错误C2143:语法错误:缺少“;”在“*”之前
1> c:\users…\linkedlist.h177:错误C2065:“T”:未声明的标识符
1> c:\users…\linkedlist.h177:错误C2923:“linkedlist”:“T”不是参数“T”的有效模板类型参数
1> c:\users…\linkedlist.h200:错误C2509:“FindBeginningNodeLoop”:成员函数未在“linkedlist”中声明
1> c:\users…\linkedlist.h5:请参阅“linkedlist”的声明
我找不到问题。非常感谢您的帮助。
谢谢。节点是LinkedList的内部类型。您有两种选择:
使用尾部返回类型,其中返回类型在类的范围内:
LinkedList<T>::FindBeginningNodeLoop()->node* { .... }
或者在类定义之外引用该类时使用该类的作用域:
template <class T>
typename LinkedList<T>::node* LinkedList<T>::FindBeginningNodeLoop() { .... }
^^^^^^^^^^^^^^^
除此之外,您还需要使用typename来指定节点是一种类型,有关详细信息,请参阅
如果编译器不支持C++11或C++14,则需要第二个版本。您在LinkedList类中声明了struct node。名称节点本身不可见,每次在类定义之外使用时,它的前面都应加上LinkedList::
此外,还需要使用typename关键字来区分类型和最终存在的同名变量。这是我的编译器发出的唯一错误消息,verbatim。blah.cpp:24:1:错误:未知类型名称'node'节点*LinkedList::FindBegingNodeLoop您发布的代码中只有47行。第177行在哪里?在我添加findbegingningnodeloop函数之前,代码的可能副本在编译时没有错误。我知道问题只与这个函数有关。别忘了类型名称。非常感谢!代码编译没有问题!值得一提的是,后面的返回类型->节点*也可以工作,噪音更小。@MikeSeymour给出了c++11。非常感谢!现在代码编译没有错误。这不是为什么需要typename。问题代码中没有提到同名变量,也没有理由存在此类变量。typename是必需的,因为node是一个依赖名称。好吧,当问题是我无法调试简单模板时,转到标准术语的详细信息是一件过分的事情。好吧,如果你不想用大字吓唬OP,然后,也许您可以声明typename是必需的,因为他们还不需要关心这些原因。我看不出关于同名变量的错误语句有什么帮助。