簡體   English   中英

(C++)得到以下編譯錯誤:無法轉換'DoubleNode<int> ' 到 ' 雙節點<int> *' 在初始化中</int></int>

[英](C++) Getting the following compilation error: cannot convert 'DoubleNode<int>' to 'DoubleNode<int>*' in initialization

我正在嘗試編譯一個雙向鏈表程序,在插入 function 時出現以下錯誤。

DoublyLinkedList.cpp:23:26: error: cannot convert 'DoubleNode<int>' to 'DoubleNode<int>*' in initialization
   23 |    DoubleNode<ItemType>* prevPtr = getAtPos(position - 1);
      |                          ^~~~~~~
      |                          |
      |                          DoubleNode<int>

相關代碼行:

DoubleNode<ItemType>* newNodePtr = new DoubleNode<ItemType>(item);
if (position == 1){
    // insert new double node at the begining of the chain
    newNodePtr->setNext(headPtr);
    headPtr = newNodePtr;
}
else{
    // find node that will be before new node
    DoubleNode<ItemType>* prevPtr = getAtPos(position - 1);
    newNodePtr->setNext(prevPtr->getNext());
    prevPtr->getNext()->setPrev(newNodePtr);
    newNodePtr->setPrev(prevPtr);
    prevPtr->setNext(newNodePtr);

getAtPost function:

template<class ItemType>
DoubleNode<ItemType> DoublyLinkedList<ItemType>::getAtPos(const int& position) const
{
    // count from begining of chain
    DoubleNode<ItemType>* curPtr = headPtr;
    for (int i = 1; i < position; i++){
        curPtr = curPtr->getNext();
    }
    return *curPtr;
}  // end getAtPos

您的getAtPos()方法從列表中返回DoubleNode<ItemType> object 的副本,而不是返回指向原始 object 的指針,這正是調用者實際期望的。

您也沒有處理position參數指定超出列表范圍的索引的可能性。

試試這個:

template<class ItemType>
DoubleNode<ItemType>* DoublyLinkedList<ItemType>::getAtPos(int position) const
{
    DoubleNode<ItemType>* curPtr = nullptr;

    if (position >= 0) {
        curPtr = headPtr;
        while ((curPtr) && (position > 0)) {
            curPtr = curPtr->getNext();
            --position;
        }
    }

    if (!curPtr)
        return nullptr; // or throw an exception...

    return curPtr;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM