我目前正在编写要在我的 BFS 算法中使用的 Tile 类。我需要一个 cameFrom
变量,它可以在我遍历网格时跟踪图 block 的来源。它不应该在一开始就被初始化,因为我们不知道它一开始是从哪里来的。当我运行我的 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
我的 Tile.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)
{
}
关于c++ - 对我的 BFS tile 类中的引用和指针感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27999974/