c++ 自定义类模版产生链接错误的原因

来源:互联网 发布:数据质量管控管理办法 编辑:程序博客网 时间:2024/05/21 07:59

今天调试c++ primer 上的程序,出现了莫名奇妙的链接错误~

程序很简单就是定义一个数组类模版~ 我将类定义和类实现分别放在array.h 和array.cpp两个文件中~换了三个编译器也不行~

 

下面是在vs2005中的错误提示:

1>test.obj : error LNK2019: 无法解析的外部符号 "void __cdecl swap<int>(class Array<int> &,int,int)" (??$swap@H@@YAXAAV?$Array@H@@HH@Z),该符号在函数 _main 中被引用
1>test.obj : error LNK2019: 无法解析的外部符号 "public: __thiscall Array<int>::Array<int>(class Array<int> const &)" (??0?$Array@H@@QAE@ABV0@@Z),该符号在函数 _main 中被引用
1>test.obj : error LNK2019: 无法解析的外部符号 "public: __thiscall Array<int>::Array<int>(int *,int)" (??0?$Array@H@@QAE@PAHH@Z),该符号在函数 _main 中被引用
1>test.obj : error LNK2019: 无法解析的外部符号 "public: __thiscall Array<int>::Array<int>(int)" (??0?$Array@H@@QAE@H@Z),该符号在函数 _main 中被引用
1>test.obj : error LNK2019: 无法解析的外部符号 "public: int & __thiscall Array<int>::operator[](int)" (??A?$Array@H@@QAEAAHH@Z),该符号在函数 "void __cdecl show<int>(class Array<int> &)" (??$show@H@@YAXAAV?$Array@H@@@Z) 中被引用

 

 

下面是在dev c++中的错误提示:

  [Linker error] undefined reference to `Array<int>::Array(int)'

  [Linker error] undefined reference to `Array<int>::Array(int*, int)'

  [Linker error] undefined reference to `Array<int>::Array(Array<int> const&)'

  [Linker error] undefined reference to `void swap<int>(Array<int>&, int, int)'

  [Linker error] undefined reference to `void swap<int>(Array<int>&, int, int)'

  [Linker error] undefined reference to `Array<int>::operator[](int)'

下面是在code::blocks里的错误提示:

||=== testarray, Debug ===|
obj/Debug/test.o||In function `main':|
/testArray/testarray/test.cpp|19|undefined reference to `Array<int>::Array(int)'|
/testArray/testarray/test.cpp|20|undefined reference to `Array<int>::Array(int*, int)'|
/testArray/testarray/test.cpp|21|undefined reference to `Array<int>::Array(Array<int> const&)'|
/testArray/testarray/test.cpp|22|undefined reference to `void swap<int>(Array<int>&, int, int)'|
/testArray/testarray/test.cpp|23|undefined reference to `void swap<int>(Array<int>&, int, int)'|
obj/Debug/test.o||In function `_Z4showIiEvR5ArrayIT_E':|
)]+0x2b)||undefined reference to `Array<int>::operator[](int)'|
||=== Build finished: 6 errors, 0 warnings ===|

三个环境提示的错误差不多~

后来经过一个高手指点才知道~类模版比较特殊,因为在编译前需要用定义的类型来替代类型占位符所以类的定义和实现必须都是可见的。解决方法也很简单,将类的定义和实现都写在头文件里就行了。

原创粉丝点击