繁体   English   中英

在模板化类的副本构造函数中使用默认值时出错

[英]Error with using defaults in copy constructor of a templated class

我有以下模板化的类,

template <typename Real>
class Marker {

 typedef Wm5::Vector3<Real> Position ;
 typedef Wm5::Vector3<Real> Normal ;
 typedef Wm5::Vector3<Real> Color ;

 public:

  Marker(int id = -1, Position position = Wm5::Vector3<Real>::ZERO, Normal normal = Wm5::Vector3<Real>::ZERO, Color color = Wm5::Vector3<Real>::ZERO)
: id_(id), position_(position), normal_(normal), color_(color), cluster_(-1) {}

  ~Marker() {}

 private:

  int id_ ;
  Position position_ ;
  Normal normal_ ; 
  Color color_ ;
  int cluster_ ;

};


template <typename T> 
class MarkerSet {

    typedef Marker<T> MarkerT ;      
    typedef std::vector<MarkerT> MarkerVector ;

public:

    MarkerSet::MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) 
   {id_ = id; markers_ = markers;}      

   MarkerSet::~MarkerSet() {}

private:

    int id_ ;   
    MarkerVector markers_ ;

} ;

当我尝试通过创建MarkerSet对象时

MarkerSet<double> markerSet ; 

收到此链接器错误,

error LNK2001: unresolved external symbol "public: __thiscall     MarkerSet<double>::MarkerSet<double>(int,class std::vector<class Marker<double>,class std::allocator<class Marker<double> > >)" (??0?$MarkerSet@N@@QAE@HV?$vector@V?$Marker@N@@V?$allocator@V?$Marker@N@@@std@@@std@@@Z)

如果有人能就我做错的事情为我提供了正确的指导,我将万分感谢。

编辑:

好的,我将其范围缩小到相当奇怪的程度。

在.h中

  MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) 
{id_ = id; markers_ = markers;}    

建造良好

而不是在.h中

 MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) ;

在.cpp中

 template <typename T>
 MarkerSet<T>::MarkerSet(int id, MarkerVector markers) {

  id_ = id ;
  markers_ = markers ;

}

错误以上述方式排除。

有什么想法吗?

您可以尝试使用其他编译器吗? 我尝试使用它,以下代码对我来说适用于gcc。 我淘汰了Wm5成员,因为我没有这些成员。 粘贴标题和cpp:

测试

#include <vector>

template <typename Real>
class Marker {

 public:

  Marker(int id = -1,int _position=1)
    : id_(id), position(_position){}

  ~Marker() {}

 private:

  int id_ ;
  int position ;
  Real r;

};


template <typename T> 
class MarkerSet {

    typedef Marker<T> MarkerT ;      
    typedef std::vector<MarkerT> MarkerVector ;

public:

    MarkerSet(int id = -1, MarkerVector markers = MarkerVector()) 
      {id_ = id; markers_ = markers;std::cout<<"Called"<<std::endl;}      

   ~MarkerSet() {}

private:

    int id_ ;   
    MarkerVector markers_ ;

} ;

测试文件

#include <iostream>
#include <vector>
#include "test.h"

using namespace std;


int main(int argc, const char **argv) {
  cout<<"Hello"<<endl;
  MarkerSet<double> ms;
  return -1;

}

命令:

bash$ ./test
Hello
Called
bash$ 

模板类定义必须在标题中:

为什么C ++模板定义需要放在标题中?

可能是因为您不#include实际的构造器主体,以使链接器不会为MarkerSet<double>::MarkerSet<double>(int,class std::vector<class Marker<double>,class std::allocator<class Marker<double> > >)"吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM