这是一个链接列表的演示,我定义了一个 Node 结构,它的指针作为头,但是编译器说:in--valid use of non-static member at the place:
Node* head;
此外,如果我不预先声明 struct Node
,它将报告未声明的节点。
代码如下:
#ifndef LINKLIST_H
#define LINKLIST_H
template<typename T>
class LinkList
{
struct Node; //why declaration is required here ???
public:
// member function
Node* Find(T x);
//.....
private:
struct Node
{
T data;
Node* next;
// Node():next(NULL){}
Node(const T& d=0, Node* n=NULL):data(d),next(n){}
};
Node* head; //ERROR ?????? why?
};
template<typename T>
typename LinkList<T>::Node* LinkList<T>::Find(T x)
{
Node* ptr=head->next;
//.....
endif//LINKLIST_H
运行时错误:
||=== Build: Release in Broken Keyboard (compiler: GNU GCC Compiler) ===|
include\LinkList.h|41|error: invalid use of non-static data member 'LinkList<T>::head'|
include\LinkList.h|22|error: from this location|
include\LinkList.h|41|error: invalid use of non-static data member 'LinkList<T>::head'|
include\LinkList.h|95|error: from this location|
include\LinkList.h|95|error: default argument given for parameter 1 of 'void LinkList<T>::Insert(T, LinkList<T>::Node*)' [-fpermissive]|
include\LinkList.h|22|error: after previous specification in 'void LinkList<T>::Insert(T, LinkList<T>::Node*)' [-fpermissive]|
include\LinkList.h|95|error: default argument given for parameter 2 of 'void LinkList<T>::Insert(T, LinkList<T>::Node*)'|
include\LinkList.h|22|error: after previous specification in 'void LinkList<T>::Insert(T, LinkList<T>::Node*)'|
||=== Build failed: 8 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
最佳答案
由于在提供 Node 定义之前要在 Find 方法中使用它,因此需要对 struct Node 进行第一个前向声明。 但是你不应该在 Node *head 中有错误。我已经在 Visual Studio 2015 中试过你的代码并在 main 中实例化模板,没有错误。
你的编译器版本是多少?
阿隆。
关于c++ - 嵌套结构 : with invalid use of non-static member when define struct pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34347632/