1

由于我的 c++ 程序中出现以下错误,我想到了这个问题

#include <iostream>
using namespace std;
class Test
{
private:
  int x;
public:
  Test(int x = 0) { this->x = x; }
  void change(Test *t) { this = t; }
  void print() { cout << "x = " << x << endl; }
};

int main()
{
  Test obj(15);
  Test *ptr = new Test (100);
  obj.change(ptr);
  obj.print();
  return 0;
}

错误:

main.cpp:18:31: error: lvalue required as left operand of assignment
   18 | void change(Test *t) { this = t; }
      |    

我搜索了这个错误,发现它通常发生在我们尝试将赋值运算符左侧的常量分配给右侧的变量时。如果我错了,请纠正我。

谢谢

4

3 回答 3

0

从 cppreferencethis

关键字this是纯右值表达式,其值是隐式对象参数的地址(调用非静态成员函数的对象)。

您不能分配给rvalues(例如1 = obj无效)。因此,您必须取消引用this并分配。

*this = *t;

要回答问题的标题,

this类和对象中使用的关键字是常量指针?

不它不是。即使标记了成员函数,const它仍然是指向const对象的指针。

从cppereference,

this的成员函数中的类型class XX*(指向 X 的指针)。如果成员函数是 cv 限定的,则类型thiscv X*(指向相同 cv 限定的 X 的指针)。

于 2021-12-04T05:56:26.313 回答
0

根据9.3.2 this 指针 [class.this]

1 在非静态(9.3) 成员函数的主体中,关键字this纯右值表达式,其值是调用该函数的对象的地址。[...]

所以正如错误所说,左边应该是一个左值,但你给它一个纯右值,因为它change是一个非静态成员函数,并且在任何非静态成员函数中,关键字this都是根据上面引用的语句的纯右值。因此错误。

但是可以修改this指向的对象,如下图:

#include <iostream>
using namespace std;
class Test
{
private:
  int x;
public:
  Test(int x = 0) { this->x = x; }
  void change(Test *t) { *this = *t; }//THIS WORKS 
  void print() { cout << "x = " << x << endl; }
};

int main()
{
  Test obj(15);
  Test *ptr = new Test (100);
  obj.change(ptr);
  obj.print();
  return 0;
}

请注意,在上面的示例中,我已替换this = t;

*this = *t;//this time it works because now the left hand side is an lvalue 

这次程序有效,因为现在左边是一个左值

更多解释

IBM 的 this 指针文档中,

this参数的类型 Test *const。也就是说,它是一个指向对象的常量指针 。现在,由于它是常量指针,因此您不能使用. 因此错误。Test this = t;

同样,从微软的 this 指针文档中,

this指针始终是const 指针。它不能被重新分配

所以这也解释了你得到的错误。

于 2021-12-04T05:58:10.147 回答
0

在非 const 成员函数中,this 的类型为“Type* const this”,而在 const 成员函数中为“const Type* const this”。因此,您不能更改 const this 值以使其指向另一个地址。您可以使用下面的代码来模拟它:

struct A{
    int a;
};
int main() {
      A* const p = new A();
      p = new A();    
      return 0;
}

你会得到同样的错误在此处输入图像描述

下图展示了 const 成员函数和非 const 成员函数中 this 的类型: 在此处输入图像描述

在此处输入图像描述

于 2021-12-04T06:13:58.547 回答