我在檔案中有以下代碼.h
:
class Test1 {
struct A1 {
int x;
};
static const A1 a1;
};
template <class T>
class Test2 {
struct A2 {
int x;
};
static const A2 a2;
};
我在檔案中定義了兩者a1
的值:a2
.cpp
const Test1::A1 Test1::a1 = { 5 };
template<class T>
const Test2<T>::A2 Test2<T>::a2 = { 5 };
奇怪的是,Test1
一切正常,但Test2
我在檔案的最后一行收到以下錯誤.cpp
:
Error C2061 syntax error: identifier 'A2'
Test1
和之間的唯一區別Test2
是它Test2
有一個模板。為什么這是一個問題,我該如何解決?此外,這也有效:
test.h
struct A3 {
int x;
};
template <class T>
class Test3 {
static const A3 a3;
};
test.cpp
template<class T>
const A3 Test3<T>::a3 = { 5 };
所以問題在于使用模板類中定義的結構,但我無法找出問題所在。
(我正在用 c 14 編譯。)
uj5u.com熱心網友回復:
該修復程式由編譯器建議,請在閱讀編譯器訊息時更加小心。
<source>(17): warning C4346: 'A2': dependent name is not a type
<source>(17): note: prefix with 'typename' to indicate a type
<source>(17): error C2061: syntax error: identifier 'A2'
<source>(17): error C2143: syntax error: missing ';' before '{'
<source>(17): error C2447: '{': missing function header (old-style formal list?)
要么
<source>:17:7: error: missing 'typename' prior to dependent type name 'Test2<T>::A2'
const Test2<T>::A2 Test2<T>::a2 = { 5 };
^~~~~~~~~~~~
typename
1 error generated.
這意味著正確的代碼:
template<class T>
const typename Test2<T>::A2 Test2<T>::a2 = { 5 };
閱讀更多:為什么我們在這里需要 typename?.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/443090.html