繁体   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