繁体   English   中英

C ++中的指针和引用出现问题

[英]Trouble with pointers and references in C++

我有一个PolygonList和Polygon类型,它们是std :: lists点列表或点列表列表。

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中的第一个Polygon,并将新的Point推入其中。

所以我尝试将polygonList的前面设置为一个名为currentPolygon的多边形,如下所示:

 Polygon currentPolygon = polygonList.front();
 currentPolygon.push_front(somePoint);

现在,我可以将点添加到currentPolygon,但是这些更改最终并没有反映在polygonList的同一多边形中。 是currentPolygon简直是在polygonList前面的多边形的副本 当我以后遍历polygonList时,未显示我添加到currentPolygon的所有点。

如果我这样做,它将起作用:

polygonList.front().push_front(somePoint);

为什么这些不一样?如何创建对物理前多边形的引用而不是其副本?

像这样:

 Polygon &currentPolygon = polygonList.front();
 currentPolygon.push_front(somePoint);

名称前的&符号表示这是参考。

 Polygon currentPolygon = polygonList.front();

由于类Polygon不会重载赋值运算符,因此编译器会为您静默地执行此操作,并在此行将其实例化。

在编译器引入的版本中实现的赋值运算符的默认行为是制作对象的副本。

您可能应该首先将列表定义为指针列表:

typedef std::list<Point> Polygon;
typedef std::list<Polygon*> PolygonList;

这样避免了昂贵的复制。 当然,您随后需要进行一些手动内存管理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM