对我的 BFS 磁贴类中的引用和指针感到困惑

Confused about references and pointers in my BFS tile class

本文关键字:指针 引用 BFS 我的      更新时间:2023-10-16

我目前正在编写一个要在我的BFS算法中使用的Tile类。我需要一个cameFrom变量,它将在我遍历网格时跟踪瓷砖的来源。它不应该在开始时初始化,因为我们不知道它一开始是从哪里来的。当我运行我的BFS算法时,它会不断更新。

Error 1 error C2758: 'Tile::cameFrom' : a member of reference type must be initialized

有谁知道出了什么问题?

这是我的Tile.hpp:

#ifndef _TILE_H
#define _TILE_H
class Tile
{
    public:
        Tile(int x, int y);
        ~Tile();
        int GetX();
        int GetY();
        bool IsWall();
        bool IsVisited();
        void SetCameFrom(Tile& cameFrom);
        Tile& GetCameFrom();
        void ToggleWall();
        void ToggleVisited();
    private:
        int x;
        int y;
        bool isWall;
        bool isVisited;
        Tile& cameFrom;
};
#endif

我的磁贴.cpp:

#include "Tile.hpp"

Tile::Tile(int x, int y) {
    this->x = x;
    this->y = y;
    this->isWall = false;
    this->isVisited = false;
}
Tile::~Tile() {}
int Tile::GetX() {
    return x;
}
int Tile::GetY() {
    return y;
}
bool Tile::IsWall() {
    return isWall;
}
bool Tile::IsVisited() {
    return isVisited;
}
void Tile::SetCameFrom(Tile& cameFrom) {
    this->cameFrom = cameFrom;
}
Tile& Tile::GetCameFrom() {
    return cameFrom;
}
void Tile::ToggleWall() {
    isWall = !isWall;
}
void Tile::ToggleVisited() {
    isVisited = true;
}

首先,必须初始化引用,因此必须在构造函数中设置它。其次,您无法重新分配引用,因此您的SetCameFrom函数将不起作用。为此使用指针。

Tile * cameFrom;
但是,在

构造函数中初始化指向 0(或 C++11) 中的 nullptr)的指针也很好。

Tile::Tile(int p_x, int p_y):
    x(p_x), 
    y(p_y),
    cameFrom(0),
    isWall(false),
    isVisited(false)
{
}

它不应该在开始时初始化,因为我们不知道它一开始来自哪里

然后,您只能使用指针作为必须初始化的引用。当您在指针引用之间进行选择时,请务必询问以下三个问题。

  • 我是否需要一些东西,我需要在声明时执行初始化。

  • 我是否需要这样做来引用其生命周期中的其他变量(赋值)。

  • 我是否需要使该对象指向 NULL。

如果任何问题的答案为"是",则选择指针其他引用。