【问题标题】:How to call a class recursively in c++?如何在 C++ 中递归调用一个类?
【发布时间】:2018-04-19 06:18:48
【问题描述】:

你好,这是代码:

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

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

【问题讨论】:

标签: c++ data-structures fibonacci-heap


【解决方案1】:

根据此处的变量名称和初始化程序,我假设您正在将我的 Java Fibonacci heap 改编为 C++。 :-) 如果是这样,祝你好运!

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

First_entry.mPrev.mNext

将被改写为

First_entry->mPrev->mNext

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

【讨论】:

  • 嗯,是的,我正在尝试将其改编为 C++。谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2020-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多