簡體   English   中英

如何在C ++中通過引用復制對象?

[英]How to copy an object by reference in C++?

我有以下情況。 那就是我想要做的:

std::vector < Shape > shapesArr;
Shape *shape = new Shape();
shape->someParam = someValue;
shapesArr.push_back( Shape );

// ...

Shape *shape2 = new Shape();
shape2 = shapesArr[ 0 ]; // <-- here I need a copy of that object to shapeA

delete[] shapesArr;
delete shape2; // <-- error, because it has already freed. It would be nice if I had a copy of shapesArr[ 0 ] in my shape2

如何正確地將該對象復制到shape2? 我需要該對象的兩個副本,這些副本將分別存儲在shapesArr [0]和shape2中。

您可以使用Shape *shape2 = new Shape(shapesArr[0]); 創建副本。

您的代碼中有兩個錯誤:

第一:

std::vector < Shape > shapesArr;
Shape *shape = new Shape();
shape->someParam = someValue;
// you should push *shape, because Shape is just the class name
// and shape is a Shape* type pointer
// you can shapesArr.push_back( *shape );
shapesArr.push_back( Shape );

其次,您不能刪除矢量,因為您沒有新建矢量,如果要擦除矢量中的所有元素,請使用shapesArr.clear()shapesArr.erase(shapesArr.begin(),shapesArr.end());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM