c++data-structuresfibonacci-heap

How to call a class recursively in c++?


Hello this is the code:

template <class T> class FibonacciHeap{
public:
    class Entry{
        public:
            // Returns the element represented by this heap entry.
            T getValue(){
                return mElem;
            }

            // Sets the element associated with this heap entry.
            void setValue(T value){
                    mElem = value;
            }

            // Returns the priority of this element.
            double getPriority(){
                return mPriority;
            }

        private:
            int mDegree = 0;                // Number of children
            bool mIsMarked = false;         // Whether the node is marked

            Entry mNext;                    // Next element in the list
            Entry mPrev;                    // Previous element in the list

            Entry mChild;                   // Child node, if any
            Entry mParent;                  // Parent node, if any
            T mElem;                        // Element being stored here
            double mPriority;               // Its priority

            //Constructs a new Entry that holds the given element with the indicated priority.
            Entry(T elem, double priority){
                mNext = mPrev = this;
                mElem = elem;
                mPriority = priority;
            }
    };
    ...

In the Class "Entry" I want to call Entry recursively, so I can use:

    First_entry.mPrev.mNext

I know this works in Java, but when I compile this in c++, I get:

    error: 'FibonacciHeap<T>::Entry::mNext' has incomplete type

Does anyone know how to fix this or work around this?


Solution

  • Based on the variable names and initializers here, I'm assuming you're adapting my Java Fibonacci heap into C++. :-) If so, best of luck!

    In Java, if you have a variable of type Entry, it acts like a C++ variable of type Entry* in that it's a pointer to another Entry object rather than an honest-to-goodness Entry object. As a result, in the definition of the Entry class, you should adjust the fields so that they're of type Entry* rather than Entry. Similarly, instead of using the . operator to select fields, you'll want to use the -> operator. So

    First_entry.mPrev.mNext
    

    would be rewritten as

    First_entry->mPrev->mNext
    

    Don't forget to explicitly initialize the Entry pointers to nullptr - Java does this automatically, which is why there are no initializers in the Java version. However, C++ gives uninitialized pointers garbage values, so make sure to give mChild and mParent an explicit nullptr value.