如何在模板类之外定义构造函数 [英] How to defined constructor outside of template class

查看:1288
本文介绍了如何在模板类之外定义构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在类外定义模板类的constructor\destructor,我得到链接器错误。是不允许的?
我使用Visual studio 2010。



错误
1> main.obj:error LNK2019:未解析的外部符号public:__thiscall Tree ::〜

1> main.obj:error LNK2019:unresolved external(void)符号public:__thiscall Tree :: Tree(void)(?? 0?$ Tree @ H @@ QAE @ XZ)在函数_main中引用



文件

 模板< class T> 
class Tree {
public:
Tree(void);
〜Tree(void);
T x;
};

.cpp文件

  #includeTree.h

template< class T> Tree< T> :: Tree(void){
}

template< class T> Tree< T> ::〜Tree(void){
}

文件

  #includeTree.h
int main(){
Tree< int& t;
return 0;
}


解决方案

在您包含的文件中实现。您不能分离模板类声明和实现,然后只包括头文件。



对于模板,该类不会被编译,直到它被使用。所以没有这样的事情,编译的模板类可以链接。每次使用模板时,都必须针对不同类型进行编译。并且由于编译器没有访问的实现,它不知道如何编译它...


I get linker error if I define constructor\destructor of template class outside the class. Is it not allowed? I use Visual studio 2010.

error 1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Tree::~Tree(void)" (??1?$Tree@H@@QAE@XZ) referenced in function _main

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Tree::Tree(void)" (??0?$Tree@H@@QAE@XZ) referenced in function _main

In .h file

template <class T>
class Tree{
public:
    Tree(void);
    ~Tree(void);
    T x;
};

in .cpp file

#include "Tree.h"

template <class T> Tree<T>::Tree(void){
}

template <class T> Tree<T>::~Tree(void){
}

in main.cpp file

#include "Tree.h"
int main(){
    Tree<int> t;
    return 0;
}

解决方案

Templates need to be declared and implemented in the file you include. You cannot separate template class declaration and implementation and then only include the header file.

With templates, the class is not compiled until it's used. So there is no such thing as a compiled template class that can be linked against. Each time you use a template, it has to be compiled for a different type. And since the compiler does not have access to the implementation, it does not know how to compile it...

这篇关于如何在模板类之外定义构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆