Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading