嵌套结构:在定义结构指针时使用了无效的非静态成员

Nested struct: with invalid use of non-static member when define struct pointer

本文关键字:结构 无效 静态成员 定义 指针 嵌套      更新时间:2023-10-16

这是一个链表的演示,我定义了一个Node结构,它的指针是head,但编译器说:in——在这个位置有效使用非静态成员:

Node* head;

此外,如果我不预先声明struct Node,它将报告未声明的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) ===|
includeLinkList.h|41|error: invalid use of non-static data member 'LinkList<T>::head'|
includeLinkList.h|22|error: from this location|
includeLinkList.h|41|error: invalid use of non-static data member 'LinkList<T>::head'|
includeLinkList.h|95|error: from this location|
includeLinkList.h|95|error: default argument given for parameter 1 of 'void LinkList<T>::Insert(T, LinkList<T>::Node*)' [-fpermissive]|
includeLinkList.h|22|error: after previous specification in 'void LinkList<T>::Insert(T, LinkList<T>::Node*)' [-fpermissive]|
includeLinkList.h|95|error: default argument given for parameter 2 of 'void LinkList<T>::Insert(T, LinkList<T>::Node*)'|
includeLinkList.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)) ===|

structNode的第一个正向声明是必需的,因为在提供Node定义之前,您在Find方法中使用它。但是您不应该在Node*头中出现错误。我已经在Visual Studio 2015中尝试了您的代码,并在main中实例化了模板,没有错误。

你的编译器版本是什么?

阿隆。