如何将单件链表的push_front()方法实现为其成员函数?下面的代码无法编译(error: lvalue required as left operand of assignment),因为您无法分配给this指针。如何解决这个问题?

#include<algorithm>
using namespace std;

class ListElem{
public:
    ListElem(int val): _val(val){}
    ListElem *next() const { return _next; }
    void next(ListElem *elem) { _next = elem; }
    void val(int val){ _val = val; }
    int val() const { return _val;}
    void print();
    void push_front(int);
private:
    ListElem *_next;
    int _val;
};

void ListElem::push_front(int val)
{
    ListElem *new_elem = new ListElem(val); //new node
    new_elem->next( this ); // new node points to old head
    this = new_elem; // make new node the new head, error!
    return;
}

void ListElem::print()
{
    ListElem *pelem = this;
    while(ListElem *pnext_elem = pelem->next())
    {
        cout << pelem->val() << ' ';
        pelem = pnext_elem;
    }
    cout << pelem->val() << endl;
}

int main()
{
    //initialization
    ListElem *head = new ListElem(1);
    ListElem *elem = head;
    for (int ix = 2; ix < 10; ++ix)
    {
        ListElem *elem_new = new ListElem(ix);
        elem -> next(elem_new);
        elem = elem_new;
    }
    head->print();

    //insert at the beginning
    head->push_front(7);
    head->print();
}

最佳答案

从逻辑上讲,push_front()必须是List类的方法,而不是ListElement类的方法

关于c++ - push_front()作为链接列表成员函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18463304/

10-13 05:34