c++ - 成员函数 C++ 的无效使用

标签 c++ linked-list

我正在尝试构建一个名为 SetList 的 STL 容器,如下所示

template
    <typename T>
class SetList
{
public:
    struct ListNode
    {
        T info;
        ListNode * next;

        ListNode(T newInfo, ListNode * newNext)
            : info(newInfo), next(newNext)
        {
        }

        static ListNode * insert(const char *s)
        {
            *head->info = "test"; //error occurs here, whenever i try to assign head: "invalid use of member ‘SetList<T>::head’ in static member function"
        }
    };

    struct iterator
    {
        typedef std::forward_iterator_tag iterator_category;
        typedef iterator self_type;
        typedef T value_type;
        typedef T& reference;
        typedef ListNode * pointer;
        typedef ptrdiff_t difference_type;
    private:
        pointer buf;
    public:
        iterator(pointer ptr)
            :buf(ptr)
        {   
        }
    };

    SetList() : head(new ListNode("", NULL)) {}
    iterator first(){return iterator(head);}
    iterator last(){return iterator(NULL);}
    ~SetList(){}

private:
    ListNode * head;
};

据我所知,这个问题与我使用的是静态的事实有关,因此 this 不存在于函数的范围内,但是从我的理解,我已经在私有(private)区域使用 ListNode *head 对此进行了补救 - 或者这是不正确的?

我正在尝试为链表构建一个简单的插入函数,但无法在没有错误的情况下访问头部。

最佳答案

由于head 不是static,每个ListNode 都有自己的head。因此,您需要 this 指针来访问 head
您可以将 head 设置为 static,但这实际上意味着所有列表都具有相同的头部,而您实际上只能有一个列表。

更好的解决方案是使 insert 而不是 static,这将允许您访问 head 并具有逻辑意义,因为您需要说出要插入哪个列表。

关于c++ - 成员函数 C++ 的无效使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35936293/

相关文章:

Java,将链表与数组进行比较

c - 单链表实现问题

c - C中节点交换位置

c - 传递 strcpy 的参数 2 使指针来自整数而不进行强制转换

C++ : BFS to calculate distance between every pair of nodes in a tree

c++ - 为什么 const_cast<iterator>(const_iterator) 在 Visual C++ 6.0 中有效,但在 Visual Studio .NET 中无效?

c++ - is_invocable_r 忽略返回参数

c++ - 为错误创建日志编写器的最佳实践

c++ - 如何访问数百万位进行散列

c - 具有链接队列输出错误的 BST