类模板相互引用的问题(错误:缺少类型说明符-假定为int。注意:C++不支持默认int)


问题描述:


现在有两个模板类(头文件A.h为1~14行,头文件B.h为15~27行):

  1: ///////////////////////////////////////////
  2: // file A.h
  3: //
  4: #include "B.h"
  5: 
  6: template <class T>
  7: class A
  8: {
  9: public:
 10:     T a;
 11:     B b_ptr;
 12:     A(): a(0), b_ptr(NULL) {}
 13: };
 14: 
 15: ///////////////////////////////////////////
 16: //file B.h
 17: //
 18: #include "A.h"
 19: 
 20: template <class T>
 21: class B
 22: {
 23: public:
 24:     T b;
 25:     A a_ptr;
 26:     B(): b(0), b_ptr(NULL) {}
 27: };

此处编译会报如下错误:

error C4430:缺少类型说明符-假定为int。注意:C++不支持默认int

error C2143:语法错误:缺少“,”(在”<”的前面)


解决办法:

在A.h中对类B进行前向声明,在B.h中对类A进行前向声明,如下代码所示(代码7~8行和25~26行):

  1: ///////////////////////////////////////////
  2: // file A.h
  3: //
  4: #include "B.h"
  5: 
  6: // forward statement
  7: template <class T>
  8: class B;
  9: 
 10: template <class T>
 11: class A
 12: {
 13: public:
 14:     T a;
 15:     B b_ptr;
 16:     A(): a(0), b_ptr(NULL) {}
 17: };
 18: 
 19: ///////////////////////////////////////////
 20: //file B.h
 21: //
 22: #include "A.h"
 23: 
 24: // forward statement
 25: template <class T>
 26: class A;
 27: 
 28: template <class T>
 29: class B
 30: {
 31: public:
 32:     T b;
 33:     A a_ptr;
 34:     B(): b(0), b_ptr(NULL) {}
 35: };

关键词:

前向声明, 模板类

E-mail:www.lxl1965@hotmail.com


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM