如何在 c++ 中递归调用类



你好,这是代码:

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;
            }
    };
    ...

在类"Entry"中,我想递归调用Entry,所以我可以使用:

    First_entry.mPrev.mNext

我知道这在 Java 中有效,但是当我用 c++ 编译它时,我得到:

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

有谁知道如何解决这个问题或解决这个问题?

基于这里的变量名称和初始值设定项,我假设你正在将我的 Java 斐波那契堆改编成C++。如果是这样,祝你好运!

在Java中,如果你有一个类型为Entry的变量,它的作用类似于Entry*类型的C++变量,因为它是指向另一个Entry对象的指针,而不是一个诚实的善良Entry对象。因此,在 Entry 类的定义中,应调整字段,使其类型为 Entry* 而不是 Entry 。同样,您需要使用 -> 运算符,而不是使用 . 运算符来选择字段。所以

First_entry.mPrev.mNext

将被重写为

First_entry->mPrev->mNext

不要忘记显式初始化指向nullptrEntry指针 - Java 会自动执行此操作,这就是为什么 Java 版本中没有初始值设定项的原因。但是,C++会给出未初始化的指针垃圾值,因此请确保提供mChildmParent显式nullptr值。

最新更新