问题
The dummyNode declaration variable was working well until i wrote iterator class as nested, now it gives me an error invalid use of non-static data member, 'linkedList::dummyNode' c++, if i removed iterator class it works well template
class linkedList
{
private:
listNode<T> * head, *tail;
listNode<T> * dummyNode = new listNode<T>;
int sz = 0;
public:
class iterator
{
public:
iterator()
{
itrNode = head;
}
void operator ++ ()
{
try{
if(itrNode == dummyNode)
throw "Sorry this is the end of the list\n";
else
{
itrNode = itrNode->next;
}
}catch(const char * error)
{
cerr << error;
}
}
T& operator *()
{
return *(itrNode->value);
}
void operator -- ();
private:
listNode<T> * itrNode;
};
linkedList();
~linkedList();
linkedList(T value, int initial_size);
iterator begin();
};
回答1:
A C++ nested class do not share data with its outer class -- if there were the case, each instance of the inner class would be in a one-to-one relationship with a corresponding instance of an outer class and would thus add no extra functionality. Instead, the main purposes of nested classes are:
- Namespace meaning:
linkedlist::iterator
is more meaningful thanlinkedlist_iterator
- Depending on the C++ version standard, a nested class has extra visibility of the member objects of instances of the outer class
- Maybe others that I'm not aware of
The biggest problem in your code is the constructor of the iterator
iterator()
{
itrNode = head;
}
The data head
means nothing in the context of the inner class, because its a data member of a linkedlist
object -- again, the iterator
does not belong to an instance of the linkedlist
class. Instead the constructor should be something like
iterator(linkedlist<T>& list)
{
itrNode = list.head; // Might not work in C++03
}
There might be other changes you need to make regarding the templatization (I'm not sure; I haven't made nested templated classes before). Also, this type of constructor for the linked list should work, but doesn't follow standard paradigms. More standard would be adding functions
iterator linkedlist::begin();
iterator linkedlist::end();
to the linkedlist
class. Even better would be to create begin(linkedlist&)
and end(linkedlist&)
functions. This is explained in this following SO post.
来源:https://stackoverflow.com/questions/43437659/invalid-use-of-non-static-data-member-linkedlistintdummynode-c