关于GCC模板出现"undefined reference to"的错误

来源:互联网 发布:淘宝店铺引流工具 编辑:程序博客网 时间:2024/05/21 13:14
 

关于GCC模板出现"undefined reference to"的错误

分类: C++ 920人阅读 评论(0) 收藏 举报
referencegccclass编译器

今天晚上编译模板,将声明和实现分离开了,结果总是报“undefined reference to”的错误,调试了好久,也没发现代码中有什么错误的地方,就写了个简单的模板类,还是发现报同样的错误,郁闷了下,最后发现把声明和实现写在一起就不会出现错误了,又到晚上搜了下,结果还是真的是关于声明和实现分开的关系。

原因是由于GCC不支持模板类的分离编译,只能声明和实现写在一起编译了。

[cpp] view plaincopy
  1. #ifndef A_H_INCLUDED  
  2. #define A_H_INCLUDED  
  3. template <class Type>  
  4. class A{  
  5.     Type i;  
  6. public:  
  7.     A():i(0) { }  
  8.     A(const Type& _i):i(_i) { }  
  9.     Type& pop();  
  10.     ~A(){ }  
  11. };  
  12. #endif // QUEUE_H_INCLUDED  
 

[cpp] view plaincopy
  1. #include "A.h"  
  2. template <class Type>  
  3. Type& A<Type>::pop()  
  4. {  
  5.     return i;  
  6. }  
 

这样就会报错,是由于GCC编译器不支持模板类的分离编译

 

[cpp] view plaincopy
  1. #ifndef A_H_INCLUDED  
  2. #define A_H_INCLUDED  
  3. template <class Type>  
  4. Type& A<Type>::pop()  
  5. {  
  6.     return i;  
  7. }  
  8. template <class Type>  
  9. class A{  
  10.     Type i;  
  11. public:  
  12.     A():i(0) { }  
  13.     A(const Type& _i):i(_i) { }  
  14.     Type& pop();  
  15.     ~A(){ }  
  16. };  
  17. #endif // A_H_INCLUDED  
 

这样就不会报错了,以后在GCC写模板类的时候要记得将声明和实现放在一起哦!!!