为什么此代码显示第1行中要求的错误左值?怎么解决呢?

时间:2018-12-21 07:54:33

标签: c++ oop pointers this

// Create Trees

//make these float otherwise your position math below is truncated
for (float x = 0; x < terrainData.heightmapWidth; x++)
{
    //heightmapHeight not heightmapWidth
    for (float z = 0; z < terrainData.heightmapHeight; z++)
    {
        Terrain terrain = GetComponent<Terrain>();
        int r = UnityEngine.Random.Range(0, 500);
        if (r == 0)
        {
            TreeInstance treeTemp = new TreeInstance

            //position is local and expects value between 0 and 1
            treeTemp.position = new Vector3(x / terrainData.heightmapWidth, 0, z / terrainData.heightmapHeight),

            treeTemp.prototypeIndex = 0;
            treeTemp.widthScale = 1f;
            treeTemp.heightScale = 1f;
            treeTemp.color = Color.white;
            treeTemp.lightmapColor = Color.white;
            terrain.AddTreeInstance(treeTemp);
            terrain.Flush();
        }
    }
}

因为我们知道该指针保存了调用对象的引用。在第1行中,我试图更改调用对象的引用,但它显示错误“需要左值”。有人可以解释吗?

3 个答案:

答案 0 :(得分:5)

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

this指针是一个常量指针,用于保存当前对象的内存地址。 结果,在您的情况下,this的类型为const Test*,因此无法分配给它。这样做(如果允许的话)将有效地允许对象更改其在内存中的地址,如@Peter所述。

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

PS:this->x = t->x;可能就是您想说的。

答案 1 :(得分:1)

在这里,您为特定对象的“ this”指针分配了一个指针(此处为t)。 “此”指针为常量。指针,用于保存当前对象的内存地址。您根本无法更改对象的this指针,因为这样做实际上将更改对象在内存中的位置,并使名称保持不变。

参考-‘this’ pointer in C++

答案 2 :(得分:-1)

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