c++:赋值中的非ivalue

c++: non-Ivalue in assignment

本文关键字:ivalue 赋值 c++      更新时间:2023-10-16

嗨,我想做一个外部单链表。我有一个问题,"非我值在分配",它发生在网上"this = currP->next"我试着使它currP。接下来,它也会产生一个错误

#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;
            }
        }
 };

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()现在将返回一个指向列表其余部分开始的指针,递归算法将第一部分与最后一部分连接起来。它没有经过测试,所以一些调整可能是必要的,但我希望你能明白。

左值是语义规则。它的意思是"左值"

左值的例子有:

  • 一个变量。即"a"
  • 内存地址。"a[4]"或"*(a+8)"

this不是左值。你不能给它赋值。它是对方法调用者的引用。