C++ 传递向量<;共享\u ptr<;派生>&燃气轮机;对于期望向量的函数<;共享\u ptr<;基地>&燃气轮机;
我使用的代码结构有一个问题,如下所示(简化): 这些点用于创建多段线:C++ 传递向量<;共享\u ptr<;派生>&燃气轮机;对于期望向量的函数<;共享\u ptr<;基地>&燃气轮机;,c++,inheritance,shared-ptr,smart-pointers,C++,Inheritance,Shared Ptr,Smart Pointers,我使用的代码结构有一个问题,如下所示(简化): 这些点用于创建多段线: class SPolyline { public: SPolyline(const vector<shared_ptr<SPoint>>& points) { // points are cloned into _points} protected: vector<shared_ptr<SPoint>> _points; }; class Poly
class SPolyline
{
public:
SPolyline(const vector<shared_ptr<SPoint>>& points) { // points are cloned into _points}
protected:
vector<shared_ptr<SPoint>> _points;
};
class Polyline3D : SPolyline
{
public :
Polyline3D(const vector<shared_ptr<Point3D>>& points) : SPolyline(points) // doesn't compile
};
类SPolyline
{
公众:
SPolyline(const vector&points){//点被克隆到_points}
受保护的:
矢量点;
};
类Polyline3D:SPolyline
{
公众:
Polyline3D(常量向量和点):SPolyline(点)//不编译
};
当我试图编译带有此错误的Polyline3D时,VS2010拒绝我
error C2664: 'SPolyline::SPolyline(const std::vector<_Ty> &)' : cannot convert parameter 1 from 'const std::vector<_Ty>' to 'const std::vector<_Ty> &'
with
[
_Ty=std::tr1::shared_ptr<SPoint>
]
and
[
_Ty=std::tr1::shared_ptr<Point3D>
]
and
[
_Ty=std::tr1::shared_ptr<SPoint>
]
Reason: cannot convert from 'const std::vector<_Ty>' to 'const std::vector<_Ty>'
with
[
_Ty=std::tr1::shared_ptr<Point3D>
]
and
[
_Ty=std::tr1::shared_ptr<SPoint>
]
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
错误C2664:'SPolyline::SPolyline(const std::vector&'):无法将参数1从'const std::vector'转换为'const std::vector&'
具有
[
_Ty=std::tr1::共享
]
和
[
_Ty=std::tr1::共享
]
和
[
_Ty=std::tr1::共享
]
原因:无法从“const std::vector”转换为“const std::vector”
具有
[
_Ty=std::tr1::共享
]
和
[
_Ty=std::tr1::共享
]
没有可执行此转换的用户定义的转换运算符,或者无法调用该运算符
没有从向量
到向量
的默认转换。
知道多段线中的点需要共享所有权,如何解决此问题?我使用的
shared\u ptr
是标准的,而不是来自Boost。从容器中提取并使用迭代器
template<typename InputIterator>
Polyline3D(InputIterator begin, IntputIterator end) : SPolyline(begin ,end) {}
模板
Polyline3D(输入迭代器begin,输入迭代器end):SPolyline(begin,end){
可以为
向量实现这样的转换,但是考虑到它可能带来的微妙的灾难(想想隐式转换),没有它可能更好。您可以做的另一件事是:
class Polyline3D : public SPolyline
{
public :
Polyline3D(const vector<shared_ptr<Point3D>>& points) : SPolyline(std::vector<shared_ptr<SPoint> >(points.begin(), points.end())){}
};
class Polyline3D:public SPolyline
{
公众:
Polyline3D(常量向量和点):SPolyline(std::vector(points.begin(),points.end()){}
};
SPolyline构造函数也应该模板化吗?@undu当然可以。如果您使用的是C++11,那么可以使用继承构造函数。另外:您的所有示例在类声明的末尾都缺少分号;)非常感谢这个伟大的答案,它对我的案例非常有效,我从中学到了很多!!
class Polyline3D : public SPolyline
{
public :
Polyline3D(const vector<shared_ptr<Point3D>>& points) : SPolyline(std::vector<shared_ptr<SPoint> >(points.begin(), points.end())){}
};