我有一个 PolygonList 和一个 Polygon 类型,它们是 std::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 添加点,但这些更改最终不会反映在 PolygonList 中的同一多边形中。 currentPolygon只是polygonList前面Polygon的copy吗?当我稍后迭代 PolygonList 时,我添加到 currentPolygon 的所有点都不会显示。
如果我这样做,它就会起作用:
polygonList.front().push_front(somePoint);
为什么它们不一样?如何创建对物理前多边形的引用而不是其副本?
像这样:
Polygon ¤tPolygon = polygonList.front();
currentPolygon.push_front(somePoint);
名称前的 & 符号表示这是一个参考。
Polygon currentPolygon = polygonList.front();
由于 Polygon 类不会重载赋值运算符,因此编译器会默默地为您执行此操作并在这一行实例化它。
在编译器引入的版本中实现的赋值运算符的默认行为是复制对象。
您可能应该首先将列表定义为指针列表:
typedef std::list<Point> Polygon;
typedef std::list<Polygon*> PolygonList;
这避免了昂贵的复制。当然,然后你需要进行一些手动内存管理。
真主库尔塔森卡德西姆森尼伊森佐尔瓦拉