c++ - 向类添加复制构造函数

标签 c++ c++11 overloading copy-constructor

是否可以为我没有编写的类添加一个复制构造函数(或者换句话说重载它)?

例如,我正在使用一些具有 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/

相关文章:

c++ - 如何在调用其他函数的 const 和非常量函数之间重用代码

c++ - 在 std::chrono 时钟之间转换 time_points

c++ - Qt : CONFIG += C++11, 但 -std=c++0x

c++ - 函数重载,唯一变化是 "uint32_t"& uint64_t"在 c++ 的纯虚函数中

c# - 如何告诉构造函数它应该只使用原始类型

c++ - 使用 boost::assign 和嵌套在 std::map 中的 std::set

c++ - 数字与数字数组的差之和

c++ - 编译器支持 STL 容器中的有状态分配器

c++ - 为 Matrix 类设计迭代器

c# - 数据类型重载不同时的 .NET 代码重构