为什么此代码显示第1行中需要的错误lvalue?如何解决它


#include<iostream> 
using namespace std; 
class Test 
{ 
  private: 
  int x; 
  public: 
  Test(int x = 0) { this->x = x; } 
  void change(Test *t)
  { 
    this = t; //line 1 
  } 
  void print() { cout << "x = " << x << endl; } 
}; 
int main() 
{ 
  Test obj(5); 
  Test *ptr = new Test (10); 
  obj.change(ptr); 
  obj.print(); 
  return 0; 
} 

由于我们知道该指针持有调用对象的引用。在第1行中,我试图更改呼叫对象的引用,但它显示了一个错误"需要lvalue"。有人可以解释一下吗?

您不能将指针分配给this指针,因为它是 prvalue

this指针是一个恒定的指针,可容纳当前对象的内存地址。结果,在您的情况下,thisconst Test*型,因此不能分配给。如@Peter所述,这样做(如果允许的话)将有效地允许对象在内存中更改自己的地址。

注意:const Test*是指向常数对象的指针。它指向的对象是恒定的,而不是指针本身。

ps: this->x = t->x;可能是您要说的。

在这里,您将指针(此处t)分配给了特定对象的"此"指针。"此"指针是const。保存当前对象的内存地址的指针。您根本无法更改对象的指针,因为这样做几乎将更改对象在内存中保持名称相同的位置。

参考 - C

中的"此"指针
#include <iostream>
using namespace std;
class Test 
{ 
  private: 
  int x; 
  public: 
  Test(int x=0) 
  {
     this->x = x;
  } 
  void change(Test *t)
  { 
    t->x; //t is a pointer. so make it point to x
  } 
  void print() { cout << "x = " << x << endl; } 
}; 
 int main() 
{ 
 Test obj(5); 
 Test obj1(10); //create a new object
 Test *ptr = &obj1;//make the pointer point to obj1
 obj.change(ptr); //use change() to point to argument of obj1
 obj.print(); //print the value of obj now
 return 0; 
 } 

相关内容

最新更新