对我的 BFS 磁贴类中的引用和指针感到困惑
Confused about references and pointers in my BFS tile class
我目前正在编写一个要在我的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。
如果任何问题的答案为"是",则选择指针其他引用。
相关文章:
- 如何使用基类指针引用派生类成员
- 将常量指针引用绑定到非常量指针
- 如果非动态变量被指针引用,何时超出范围?
- 转换指针引用的字符串
- 指针引用的生存期(以 C++为单位)
- 从 unique_ptr::get 发送指针作为指针引用进入函数
- 指针/引用的 CLion 格式
- 使用模板专用化来比较指针引用
- 如何保存指向抽象基类的指针/引用,但在 c++ 中仍然可以复制
- C++初始化指针/引用/复制细微差别
- 用数组或指针引用函数?
- 指针范围问题和返回类中封装的指针向量内的指针引用
- 强制转换为指针引用是否会导致未定义的行为
- 访问由 void 指针引用的结构的成员
- C 为什么当先前的步骤引发异常时,std :: shared_ptr的指针引用会被破坏
- 动态指针引用数组由三元运算符返回值,但有异常
- 悬空指向 int 和 char* 常量的指针/引用
- C++ 二维数组和指针引用
- 通过使用指针/引用,在C++中使用向量加快计算速度
- C++非类型模板模板到函数指针/引用