我有一个 PolygonList 和一个 Polygon 类型,它们是 std::Lists of Points 或 lists of points of points。
class Point {
public:
int x, y;
Point(int x1, int y1)
{
x = x1;
y = y1;
}
};
typedef std::list<Point> Polygon;
typedef std::list<Polygon> PolygonList;
// List of all our polygons
PolygonList polygonList;
但是,我对引用变量和指针感到困惑。
例如,我希望能够引用我的多边形列表中的第一个多边形,并向其推送一个新点。
所以我尝试将 polygonList 的前面设置为一个名为 currentPolygon 的多边形,如下所示:
Polygon currentPolygon = polygonList.front();
currentPolygon.push_front(somePoint);
现在,我可以向 currentPolygon 添加点,但这些更改最终不会反射(reflect)在 polygonList 中的同一个多边形中。 currentPolygon 只是 polygonList 前面的 Polygon 的拷贝吗?当我稍后遍历 polygonList 时,我添加到 currentPolygon 的所有点都没有显示。
如果我这样做,它会起作用:
polygonList.front().push_front(somePoint);
为什么它们不一样,我如何创建对物理正面多边形的引用而不是它的拷贝?
最佳答案
像这样:
Polygon ¤tPolygon = polygonList.front();
currentPolygon.push_front(somePoint);
名称前的 & 符号表示这是引用。
关于c++ - C++ 中指针和引用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/544709/