invalid use of non-static data member 'linkedList<int>::dummyNode' c++

谁说我不能喝 提交于 2020-01-05 04:04:14

问题


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:

  1. Namespace meaning: linkedlist::iterator is more meaningful than linkedlist_iterator
  2. Depending on the C++ version standard, a nested class has extra visibility of the member objects of instances of the outer class
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!