c++ - C++ 中指针和引用的问题

标签 c++ pointers reference

我有一个 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 &currentPolygon = polygonList.front();
 currentPolygon.push_front(somePoint);

名称前的 & 符号表示这是引用。

关于c++ - C++ 中指针和引用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/544709/

相关文章:

c++ - IUpdateSearcher 性能问题

c++ - 如何重新分配三重指针

c - 为什么我可以分配一个局部变量并对其进行读取,但如果我尝试在结构中分配一个指针并读取它,则会出现段错误?

java - 通过 jni 将每个引用的参数从 C++ 传递到 Java

c++ - 如何使用 mmap 创建共享 std::vector<std::string>?

c++ - 多重声明与未定义

c++ - 无法创建对类的新实例的引用

c - 在 C 中通过引用传递结构体时出现问题

c++ - 如何比较2个FILETIME变量以查看文件是否早于30天

c - 正确释放结构