类模板相互引用的问题(错误:缺少类型说明符-假定为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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值