c++ - 如何在C++中递归调用一个类?

标签 c++ data-structures fibonacci-heap

你好,这是代码:

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 Fibonacci heap进入C++。 :-) 如果是这样,祝你好运!

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

First_entry.mPrev.mNext

将被重写为

First_entry->mPrev->mNext

不要忘记将 Entry 指针显式初始化为 nullptr - Java 会自动执行此操作,这就是 Java 版本中没有初始化程序的原因。但是,C++ 会为未初始化的指针提供垃圾值,因此请确保为 mChildmParent 提供明确的 nullptr 值。

关于c++ - 如何在C++中递归调用一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47147906/

相关文章:

python - Spark 中的无序集或类似集?

algorithm - 优先队列 - 跳过列表与斐波那契堆

c++ - if vs if constexpr inside constexpr 函数

c++ - 静态常量字符串(类成员)

c# - 非递归后序遍历

java - Java 中的 JSON 解析和数据操作

Java:使用斐波那契堆实现 Dijkstra 算法

data-structures - 在斐波那契堆中标记一些节点的目的是什么?

c++ - OSX 上的 glDrawElements CPU 使用率很高

c++ - [c++/pointers] : having objects A and B (B has vector member, 存储指向 A 的指针),知道 A 是否可以检索指向 B 的指针?