我得到一个不忽略的空值,因为它应该是错误的原因?

问题描述 投票:1回答:1

旋转功能无效,带有1 int参数。我不知道为什么会收到此错误。这只是一个带有2条语句的void函数。

[head_ptr_是私有链表变量。

getNodeAt返回给定位置“ position”的节点。由于它正在返回节点,因此我们可以从右到左访问其成员分配。在分配之前,它会完成操作数右侧的所有操作。如果我做错了,请随时修正我的知识。

template <class T>
void LinkedList<T>::rotate(int k)
{
    head_ptr_ = getNodeAt(k)->setNext(head_ptr_);//error here
    head_ptr_ = getNodeAt(k-1)->setNext(nullptr);
}//end of rotate

template<class T>
Node<T>* LinkedList<T>::getNodeAt(int position) const
{
    // Count from the beginning of the chain
    Node<T>* cur_ptr = head_ptr_;
    for (int skip = 0; skip < position; skip++)
        cur_ptr = cur_ptr->getNext();

    return cur_ptr;
}  // end getNodeAt

int main()
{
    LinkedList<int> bag1;

    for(int i = 14;i >= 10;i--)
    {
        bag1.insert(bag1.getLength(),i);
    }
    bag1.print();
    cout << endl;
    //bag1.invert();
    bag1.rotate(3);
    bag1.print();

    system("PAUSE");
    return 0;
}

错误:无效值不应被忽略

c++ error-handling linked-list void
1个回答
0
投票

错误分析:

错误:无效值不应被忽略。

这是一条GCC错误消息,表示函数的返回值为'void',但您正在尝试将其分配给非void变量。

您的特殊情况:您的setNext()最有可能返回void,并且您试图将其返回结果存储到变量中,这就是为什么您得到在您的rotate函数中发布的这两行代码中提到的错误的原因:

head_ptr_ = getNodeAt(k)->setNext(head_ptr_);//error here
head_ptr_ = getNodeAt(k-1)->setNext(nullptr);

您可以通过两种方式解决问题:第一个解决方案:更改您的代码,使其像这样,并应用必要的更改以保持相同的逻辑:

getNodeAt(k)->setNext(head_ptr_);
getNodeAt(k-1)->setNext(nullptr);

第二解决方案:更改您的setNext()函数以返回有效的指针(也不要忘记更改方法声明以返回Node指针):

template<class T>
Node<T>* LinkedList<T>::setNext(Node<T>* next)
{
    // same logic here as before
    return ptr; // where ptr is a valid pointer that you want to return
}  
© www.soinside.com 2019 - 2024. All rights reserved.