问题描述:
现在有两个模板类(头文件A.h为1~14行,头文件B.h为15~27行):
1: ///
2: // file A.h
3: //
4: #include "B.h"
5:
6: template
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
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
8: class B;
9:
10: template
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
26: class A;
27:
28: template
29: class B
30: {
31: public:
32: T b;
33: A a_ptr;
34: B(): b(0), b_ptr(NULL) {}
35: };
关键词:
前向声明, 模板类
E-mail: