2012-04-08 94 views
2

可能重复:
Where and why do I have to put the “template” and “typename” keywords?如何初始化静态成员数组类模板

#include <iostream> 
using namespace std; 

template <class T> 
class Test 
{ 
    union obj 
    { 
     union obj* next; 
     int num; 
    }; 

    static const int SZ=3; 
    static obj* volatile list[SZ]; 
}; 

template <class T> 
Test<T>::obj* volatile 
Test<T>::list[SZ]= 
{ 
    0, 0, 0 
}; 

int main() 
{ 
    return 0; 
} 

随着G ++,我得到的错误是:

 
18|error: expected constructor, destructor, or type conversion before '*' token 
+0

确实在'Test :: obj *'帮助之前添加'typename'? – 2012-04-08 04:12:57

+0

如果你在类之外声明该联合,它是否工作? – rutgersmike 2012-04-08 04:13:55

+0

两个都没问题,但我只知道后者。 – prehistoricpenguin 2012-04-08 07:15:39

回答

3

在之前添加关键字类型名称在成员的定义中。

+1

@Patatoswatter我认为在测试 ::列表中测试范围内的名称。考虑:class A {class B {}; void c(B); }; void A :: c(B){}' – bames53 2012-04-08 04:34:58

+0

@bames:你其实是对的(对不起,如果你阅读我以前的评论)。 [例如](http://ideone.com/C0ALx)。 – Xeo 2012-04-08 04:53:47

+0

@ bames53 bah,在查阅标准之前,我删除了关于'SZ'需要资格的评论。 §9.4.2[class.static.data]表示“静态数据成员定义中的初始化表达式在其类的范围内(3.3.7)”,但没有说明关于声明本身的任何内容。我也没有看到8.4.2 [dcl.array]下的任何内容。所以我认为这可能是一个GCC错误。 – Potatoswatter 2012-04-08 10:13:53

相关问题