![](/img/trans.png)
[英]How to call a class member function recursively from its own defintion in C++?
[英]How to call a class recursively in 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 Fibonacci堆改編為C ++。 :-)如果是這樣,祝您好運!
在Java中,如果您有類型為Entry
的變量,則它的作用類似於類型為Entry*
的C ++變量,因為它是指向另一個Entry
對象的指針,而不是誠實至善的Entry
對象。 結果,在Entry
類的定義中,您應該調整字段,使它們的類型為Entry*
而不是Entry
。 同樣,不要使用.
運算符以選擇字段,您將需要使用->
運算符。 所以
First_entry.mPrev.mNext
將被重寫為
First_entry->mPrev->mNext
別忘了顯式初始化nullptr
的Entry
指針-Java自動執行此操作,這就是Java版本中沒有初始化程序的原因。 但是,C ++提供了未初始化的指針垃圾值,因此請確保為mChild
和mParent
一個顯式的nullptr
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.