c++ - 嵌套结构 : with invalid use of non-static member when define struct pointer

标签 c++ struct nested static-members

这是一个链接列表的演示,我定义了一个 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/

相关文章:

java - MapStruct嵌套对象,仅当源元素不为null时创建目标对象

c++ - 链表根据给定的字符串数据类型删除节点

go - 在具有基础字段的任何结构数组上调用方法

javascript - 递归数组修改

go - 将嵌套配置 Yaml 映射到结构

c - 初始化和访问struct中的char数组

ruby-on-rails-4 - 为什么这些嵌套的无作用域 block 在 Rails 3 中工作时不能删除 Rails 4 中的 default_scope?

c++ - sfinae 远离破坏者

c++ - 旋转矩阵不是真正对称的(OpenCV)

c++ - UTF8 字符串 : simple idea to make index() lookup O(1)