将复制构造函数添加到 class
Add copy constructor to a class
是否可以为我没有写的 class 添加一个复制构造函数(或者换句话说重载它)?
例如,我正在使用一些具有 Point class 的库。我想给它添加一个复制构造函数。我不能也不想编辑它。
虚构语法:
cv::Point cv::Point::Point(const AnotherPoint& p){
return cv::Point(p.x,p.y);
}
P.S我没写AnotherPoint
也
编辑-问题背景-:
我想使用标准函数 std::copy
将 std::vector<cv::Point>
复制到另一个 std::vector<AnotherPoint>
的所有问题。所以我正在寻找一种重载复制构造函数的方法来实现它。
那是不可能的。
不过,您可以做相反的事情,即从您的类型 (AnotherPoint
) 到另一个类型 (cv::Point
) 定义隐式 conversion operator。
这样,您将能够在任何需要 cv::Point
的地方使用类型 AnotherPoint
的对象。
如果您也无法控制 AnotherPoint
,我想唯一的办法就是定义一个 独立函数 来创建一个 cv::Point
来自 AnotherPoint
.
OP 编辑后:
最终,要将 vector<cv::Point>
转换为 vector<AnotherPoint>
,您可以使用上面提到的独立函数作为 std::transform
的 unary_op
,正如@TartanLlama 所建议的。
您不能在定义后向类型添加构造函数。
将 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}; });
是否可以为我没有写的 class 添加一个复制构造函数(或者换句话说重载它)?
例如,我正在使用一些具有 Point class 的库。我想给它添加一个复制构造函数。我不能也不想编辑它。
虚构语法:
cv::Point cv::Point::Point(const AnotherPoint& p){
return cv::Point(p.x,p.y);
}
P.S我没写AnotherPoint
也
编辑-问题背景-:
我想使用标准函数 std::copy
将 std::vector<cv::Point>
复制到另一个 std::vector<AnotherPoint>
的所有问题。所以我正在寻找一种重载复制构造函数的方法来实现它。
那是不可能的。
不过,您可以做相反的事情,即从您的类型 (AnotherPoint
) 到另一个类型 (cv::Point
) 定义隐式 conversion operator。
这样,您将能够在任何需要 cv::Point
的地方使用类型 AnotherPoint
的对象。
如果您也无法控制 AnotherPoint
,我想唯一的办法就是定义一个 独立函数 来创建一个 cv::Point
来自 AnotherPoint
.
OP 编辑后:
最终,要将 vector<cv::Point>
转换为 vector<AnotherPoint>
,您可以使用上面提到的独立函数作为 std::transform
的 unary_op
,正如@TartanLlama 所建议的。
您不能在定义后向类型添加构造函数。
将 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}; });