【问题标题】:Trouble with pointers and references in C++C++ 中的指针和引用问题
【发布时间】:2009-02-13 04:20:57
【问题描述】:

我有一个 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 推送给它。

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

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

现在,我可以将点添加到 currentPolygon,但这些更改最终不会反映在 polygonList 中的同一个多边形中。 currentPolygon 只是 polygonList 前面的 Polygon 的副本吗?当我稍后遍历 polygonList 时,我添加到 currentPolygon 的所有点都没有显示出来。

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

polygonList.front().push_front(somePoint);

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

【问题讨论】:

    标签: c++ pointers reference


    【解决方案1】:

    像这样:

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

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

    【讨论】:

    • 那么,声明时只需要“&”,而不是每次使用后都需要?
    • & 是类型的一部分:“多边形 &”。所以,你只需要在声明时。
    • 大多数 C++ 样式尝试将类型修饰符附加到类型:即“Polygon& current”,即使实际语法是类型后跟修改后的名称(因此名称后面的 [] 和行噪音对于函数指针)
    【解决方案2】:
     Polygon currentPolygon = polygonList.front();
    

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

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

    【讨论】:

      【解决方案3】:

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

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

      这避免了昂贵的复制。当然,这时你需要做一些手动的内存管理。

      【讨论】:

      • 我相信大多数 std::list 都实现了浅拷贝,或者至少是 std::swap()。
      猜你喜欢
      • 1970-01-01
      • 2022-06-28
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      • 2011-07-09
      • 2015-04-21
      相关资源
      最近更新 更多