[英]How can I deal with pointer assignment compile error (error: no viable overloaded "=") in C++
I'm a rookie, and when I was doing Leetcode 21. Merge Two Sorted Lists I submitted this code:我是菜鸟,在做Leetcode 21. Merge Two Sorted Lists的时候我提交了这段代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
p1 = list1;
p2 = list2;
while (p1 && p2) {
if (p1->val <= p2->val) {
p->next = p1;
p1 = p1->next;
} else if (p2->val <= p1->val) {
p->next = p2;
p2 = p2->next;
}
p = p->next;
}
if (!p1) {
p->next = p2;
}
if (!p2) {
p->next = p1;
}
return head->next;
}
private:
ListNode* p1, p2;
ListNode* head = new ListNode(-101);
ListNode* p = head;
};
but got a compile error:但出现编译错误:
error: no viable overloaded '='
p2 = list2;
~~ ^ ~~~~~
also:还:
this->p1 = list1;
this->p2 = list2;
got the same error message.得到相同的错误信息。 But after I modified the error code (inside the
mergeTwoLists()
function) to:但是在我将错误代码(在
mergeTwoLists()
函数内)修改为:
ListNode* p1 = list1;
ListNode* p2 = list2;
The code can pass the testcases and no errors occured.该代码可以通过测试用例并且没有发生错误。
Q1 : I want to know why it is necessary to implement operator "="
for such a pointer assignment ( p1
or p2
are ListNode*
type and list1
and list2
are also ListNode*
type) issue. Q1:我想知道为什么需要为这样的指针赋值(
p1
或p2
是ListNode*
类型而list1
和list2
也是ListNode*
类型)实现operator "="
的问题。
Q2: Also can someone show me how to implement the operator "="
according to the error message(which can passed the testcases)? Q2:也有人可以告诉我如何根据错误消息实现
operator "="
(可以通过测试用例)?
Q3: Or if there is another solution (other than my above modification and implement the operator=
)to this compile error message (which can passed the testcases). Q3:或者如果这个编译错误消息(可以通过测试用例)有另一种解决方案(除了我上面的修改并实现
operator=
)。
Thanks!谢谢!
Very common error很常见的错误
ListNode* p1, p2;
should be应该
ListNode *p1, *p2;
You need to use *
on both variables to make both of them pointers.您需要在两个变量上使用
*
以使它们都成为指针。
Since this is confusing, and easily forgotten, most style guides recommend splitting the declaration.由于这令人困惑且容易被遗忘,因此大多数样式指南都建议拆分声明。
ListNode* p1;
ListNode* p2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.