问题描述:
现在有两个模板类(头文件A.h为1~14行,头文件B.h为15~27行):
1: ///////////////////////////////////////////2: // file A.h3: //4: #include "B.h"5:6: template <class T>7: class A8: {9: public:10: T a;11: B b_ptr;12: A(): a(0), b_ptr(NULL) {}13: };14:15: ///////////////////////////////////////////16: //file B.h17: //18: #include "A.h"19:20: template <class T>21: class B22: {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.h3: //4: #include "B.h"5:6: // forward statement7: template <class T>8: class B;9:10: template <class T>11: class A12: {13: public:14: T a;15: B b_ptr;16: A(): a(0), b_ptr(NULL) {}17: };18:19: ///////////////////////////////////////////20: //file B.h21: //22: #include "A.h"23:24: // forward statement25: template <class T>26: class A;27:28: template <class T>29: class B30: {31: public:32: T b;33: A a_ptr;34: B(): b(0), b_ptr(NULL) {}35: };
关键词:
前向声明, 模板类
E-mail:[email protected]
时间: 2024-10-05 05:07:52