c ++:赋值中的非左值

时间:2011-11-07 09:33:15

标签: c++ pointers

您好我想制作一个外部单链表。我有一个问题“分配中的非Ivalue”及其出现在线“this = currP-> next”我试图使它成为currP.next但它也产生错误

#include <cstdlib>
using namespace std;


struct node{
       int data;
       node *next;

       node(int i){
                data = i;
                next = NULL;
                }

       void insert(int position, node &n){
            node *currP = this;
            node *prevP= NULL;      
            for(int counter = 0; counter>=position;counter++, prevP = currP, currP = currP->next){
                    if(counter==position)
                    {
                    n.next  = currP->next;
                    currP->next = &n; 
                                         }                     
                    }

            }

       void add(node &n){
       next = &n;          
                 }
       void deleteNode(int i){
            node *currP = this;
            node *prevP = NULL;

            while(currP!= NULL){
               if(currP->data == i){
                  if(prevP == NULL) 
                      this = currP->next;
                  else{   
                      prevP->next = currP->next;
                  }                      
               }                                                  
               prevP = currP;
               currP = currP->next;
            }
        }
 };

2 个答案:

答案 0 :(得分:5)

lvalue是一个可以位于等于运算符左侧的变量。这意味着它的价值可以改变。您无法更改this的值,只是不允许,因此错误。

您可以按如下方式重写您的功能:

    node* deleteNode(int i){
        if (  this->data == i )
           return this->next;
        else
        {
           if ( this->next )
              this->next = this->next->deleteNode(i);
           else
              return this;
        }
    }

deleteNode()现在将返回指向列表其余部分开头的指针,递归算法将第一部分与最后一部分连接起来。它没有经过测试,所以可能需要进行一些调整,但我希望你明白这一点。

答案 1 :(得分:4)

左值是一种语义规则。 它的意思是“左值”。

左值的例子有:

  • 变量。即“a”
  • 内存地址。即“a [4]”或“*(a + 8)”

this不是左值。你不能给它分配任何东西。它是方法调用者的引用。

相关问题