是否可以为我没有编写的类添加一个复制构造函数(或者换句话说重载它)?
例如,我正在使用一些具有 Point 类的库。我想给它添加一个复制构造函数。我不能也不想编辑它。
虚构语法:
cv::Point cv::Point::Point(const AnotherPoint& p){
return cv::Point(p.x,p.y);
}
P.S 我没有写AnotherPoint
还有。
编辑-问题背景-:
我想复制的所有问题std::vector<cv::Point>
到另一个std::vector<AnotherPoint>
使用标准函数 std::copy
.所以我正在寻找一种重载复制构造函数的方法来实现它。
最佳答案
您不能在类型定义后为其添加构造函数。
复制 std::vector<cv::Point>
的简单方法到 std::vector<AnotherPoint>
将使用 std::transform
:
std::vector<cv::Point> cvPoints;
//cvPoints filled
std::vector<AnotherPoint> otherPoints;
otherPoints.reserve(cvPoints.size()); //avoid unnecessary allocations
std::transform(std::begin(cvPoints), std::end(cvPoints),
std::back_inserter(otherPoints),
[](const cv::Point& p){ return AnotherPoint{p.x, p.y}; });
关于c++ - 向类添加复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33755822/