[英]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 ¤tPolygon = 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.