模板的复制构造函数
Copy constructor for templates
复制构造函数在以下代码中失败。为了清晰,我已经剪辑了代码
#include <iostream>
#include <stdio.h>
#include <assert.h>
namespace my {
template <class T>
class Sptr {
private:
//some kind of pointer
//one to current obj
T* obj;
.
.
.
public:
.
.
.
Sptr(const Sptr &);
template <typename U>
Sptr(const Sptr<U> &);
.
.
.
};//Class ends
template <typename T>
template <typename U>
Sptr<T>::Sptr(U* u) {
//do something
}
template <typename T>
Sptr<T>::Sptr(const Sptr<T> ©Obj) {
//do copy constructor stuff
}
.
.
.
}
using namespace std;
using namespace my;
/* Basic Tests 1 ================================================================================ */
size_t AllocatedSpace;
class Base1 {
protected:
Base1() : derived_destructor_called(false) {
printf("Base1::Base1()n");
}
private:
Base1(const Base1 &); // Disallow.
Base1 &operator=(const Base1 &); // Disallow.
public:
virtual ~Base1() {
printf("Base1::~Base1()n");
assert(derived_destructor_called);
}
protected:
bool derived_destructor_called;
};
class Derived : public Base1 {
friend void basic_tests_1();
private:
Derived() {}
Derived(const Derived &); // Disallow.
Derived &operator=(const Derived &); // Disallow.
public:
~Derived() {
printf("Derived::~Derived()n");
derived_destructor_called = true;
}
int value;
};
这个测试代码行产生错误Sptr<Base1> sp3(sp);
void basic_tests_1() {
//size_t base = AllocatedSpace;
// Test deleting through original class.
{
// Base1 assigned from Sptr<Derived>.
{
Sptr<Base1> sp2;
{
Sptr<Derived> sp(new Derived);
// Test template copy constructor.
Sptr<Base1> sp3(sp);
sp2 = sp;
sp2 = sp2;
}
}
}
}
错误:/tmp/ccKrn1xG.o: In function `basic_tests_1()':
Sptr.cpp:(.text+0x81): undefined reference to `my::Sptr<Base1>::Sptr<Derived>(my::Sptr<Derived> const&)'
collect2: error: ld returned 1 exit status
您已经在类中声明了这个构造函数:
template <typename U>
Sptr(const Sptr<U> &);
但是你没有给出定义。错误消息说您从未定义过它。我猜错误信息是正确的。
您没有所需构造函数的定义,只有声明:
template <typename U>
Sptr(const Sptr<U> &);
你需要定义它,要么内联在类定义内,要么在类定义外,如下所示:
template <typename T>
template <typename U>
Sptr<T>::Sptr(const Sptr<U> &u) {
// do something
}
应该是
不是template <typename T> template <typename U> Sptr<T>::Sptr(const U& u) { //do something }
template <typename T> template <typename U> Sptr<T>::Sptr(U* u) { //do something }
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类