gpt4 book ai didi

c++ - 我得到一个没有被忽略的无效值,因为它应该是错误的,为什么?

转载 作者:太空宇宙 更新时间:2023-11-04 12:31:15 33 4
gpt4 key购买 nike

带有 1 个 int 参数的 rotate 函数无效。我不知道为什么会收到此错误。它只是一个带有 2 个语句的 void 函数。

head_ptr_ 是私有(private)链表变量。

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;
}

error: void value not ignored as it ought to be

最佳答案

错误分析:

error: void value not ignored as it ought to be.

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

您的具体情况:
您的 setNext() 很可能返回 void 并且您试图将它的返回结果存储到一个变量中,这就是为什么您会收到您在旋转函数中发布的这两行代码中提到的错误的原因:

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
}

关于c++ - 我得到一个没有被忽略的无效值,因为它应该是错误的,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582489/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com