2012-04-08 249 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