c++中类模板的声明和定义中把.h与.cpp分离时编译文件包含问题

来源:互联网 发布:java开发工程师 拉钩 编辑:程序博客网 时间:2024/04/30 06:30
c++中类模板的声明和定义中把.h与.cpp分离

1.声明部分

// Template_test.h
template<class T>
class CTpl  
  {
   public:
      CTpl();
virtual ~CTpl();

void Test(T t);
   };

2.实现部分
// Template_test.cpp
#include "Template_test.h"

template<class T>
CTpl<T>::CTpl()
  {
  }

template<class T>
CTpl<T>::~CTpl()
  {
  }

template<class T>
void CTpl<T>::Test(T t)
  {
  }
3.习惯错误用法
// main.cpp
#include "Template_test.h"

int main()
  {
CTpl<char> ts;
ts.Test(3);
  return 0;
  }

build时出现link错误
main.obj : error LNK2001: unresolved external symbol "public: virtual __thiscall CTpl<char>::~CTpl<char>(void)" (??1?$CTpl@D@@UAE@XZ)
main.obj : error LNK2001: unresolved external symbol "public: void __thiscall CTpl<char>::Test(char)" (?Test@?$CTpl@D@@QAEXD@Z)
main.obj : error LNK2001: unresolved external symbol "public: __thiscall CTpl<char>::CTpl<char>(void)" (??0?$CTpl@D@@QAE@XZ)

这组错误信息和project中不加入Tpl.cpp的错误信息一样,即没有CTpl<char>的实现代码
Template_test.cpp包涵到main.cpp中,问题解决


4.正确用法

// main.cpp
#include "Template_test.cpp"
int main()
{
    CTpl<char> ts;
    ts.Test(3);
    return 0;
}

5.总结
1.在使用以.h,.cpp分离实现模板类时,不能像使用普通类一样只简单的包涵.h头文件,应该在使用模板类的cpp文件中引入模板类相应的cpp文件
2.将模板类的声明与实现都放在.h中(在多个cpp中使用不同模板参数时可能会引起重复定义的编译错误)


阅读全文
0 0
原创粉丝点击