我正在尝试构建一个名为 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/