Home > database >  How can I deal with pointer assignment compile error (error: no viable overloaded "=") in
How can I deal with pointer assignment compile error (error: no viable overloaded "=") in

Time:07-03

I'm a rookie, and when I was doing Leetcode 21. Merge Two Sorted Lists I submitted this code:

/**
 * 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:

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.

Q2: Also can someone show me how to implement the operator "=" according to the error message(which can passed the testcases)?

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).

Thanks!

CodePudding user response:

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;
  • Related