我可以在函数中传递指向自己的指针吗?

时间:2013-10-25 19:51:06

标签: c++ pointers this

我有一个对象(类型为Cell),它存储指向同一类型的其他对象(网格上的邻居)的指针列表。

这是一个2D网格..作为视觉,见下文:

xxc
xcc
ccx

正中心的“c”将是一个活细胞,它位于它的东北,东,南和西南。它的邻居列表将指向这些单元格,然后指向其他方向的空指针。它看起来像这样: neighbors = {null,pointer,pointer,null,pointer,null,pointer,null) (名单的顺序是北,东,南,西,东北,东南,西南,西北)。

如果一个新单元移动到其相邻位置,例如移动到该单元格的西边,它现在看起来像这样:

xxc
ccc
ccx

我需要更新邻居列表,因此它现在有一个指向其西方单元格的指针,然后西方单元格需要更新其所有邻居,说“你好!我在这里!你现在让我作为邻居” 。因此,西方单元格将通过自己的指针列表,并在每个单词上说“以ME为您的邻居更新您的列表”。我试图将“我”指针作为指针传递给自己。这是代码..

int Cell::updateAllNeighbours(){
    //Need a pointer to myself...
    Cell * temp = &this; //how do I do this???
    for (int i=0; i<NUM_NEIGHBOURS; i++){
        if (neighbours[i] != NULL) {
            if (i==0)
                neighbours[i]->updatedNeighbour(2, temp);
            else if(i==1)
                neighbours[i]->updatedNeighbour(3, temp);
            else if(i==2)
                neighbours[i]->updatedNeighbour(0, temp);
            else if(i==3)
                neighbours[i]->updatedNeighbour(1, temp);
            else if(i==4)
                neighbours[i]->updatedNeighbour(6, temp);
            else if(i==5)
                neighbours[i]->updatedNeighbour(7, temp);
            else if(i==6)
                neighbours[i]->updatedNeighbour(4, temp);
            else if(i==7)
                neighbours[i]->updatedNeighbour(5, temp);
        }
    }
}

所以我试图调用updatedNeighbour函数并说“在位置x [数字],你需要把这个指针放在你的邻居列表中”。我不知道如何将指针传递给自己。

有什么想法?对不起,这太令人困惑......

1 个答案:

答案 0 :(得分:0)

this是一个指针,而不是一个引用。所以这个(没有双关语)代码:

Cell * temp = &this;

应该是:

Cell * temp = this;

除此之外,你根本不需要temp,似乎:

if (neighbours[i] != NULL) {
  if (i==0)
    neighbours[i]->updatedNeighbour(2, this);
  else if(i==1)
    neighbours[i]->updatedNeighbour(3, this);
  // etc...
相关问题