這個問題在這里已經有了答案: 我必須在哪里以及為什么要放置“模板”和“型別名稱”關鍵字? (8 個回答) 4天前關閉。
社區在4 天前審查了是否重新打開此問題并將其關閉:
原始關閉原因未解決
我為同一類的模板化和非模板化版本提供了簡單的代碼。每個類都有相同的資料結構(Point)。Point在使用外部結構定義函式時,模板類會出現編譯問題。我用 Visual Studio 編譯了代碼。
//non-templated class is defined without a compiling error.
class Geometry1 {
public:
struct Point
{
double x = 1, y = 2, z = 3;
};
public:
Point GetAPoint()//Function is defined internally
{
Point test;
return test;
}
Point GetAnotherPoint();//Function will be defined externally
};
Geometry1::Point Geometry1::GetAnotherPoint()//This externally defined function is fine with Point
{
Point test;
return test;
}
//Now a templated version of Geometry1 is defined. Compiling error happens!!!
template<typename type>
class Geometry2{
public:
struct Point
{
type x=1, y=2, z=3;
};
public:
Point GetAPoint()//No compiling error
{
Point test;
return test;
}
Point GetAnotherPoint();//Function will be defined externally WITH compiling error
};
template<class type>
Geometry2<type>::Point Geometry2<type>::GetAnotherPoint()//This externally defined function causes compiling error with Point: Error C2061 syntax error: identifier 'Point'
{
Point test;
return test;
}
int main()
{
Geometry1 geo1;//There is compiling error for this class
Geometry1::Point p1 = geo1.GetAnotherPoint();
Geometry2<double> geo2;//Compiling error happens for this class
Geometry2<double>::Point p2 = geo2.GetAPoint();
}
完整的錯誤資訊是:
Severity Code Description Project File Line Suppression State
Error C2061 syntax error: identifier 'Point' TestClasstypedef TestClasstypedef.cpp 51
Error C2143 syntax error: missing ';' before '{' TestClasstypedef TestClasstypedef.cpp 52
Error C2447 '{': missing function header (old-style formal list?) TestClasstypedef TestClasstypedef.cpp 52
Error C2065 'geo1': undeclared identifier TestClasstypedef TestClasstypedef.cpp 60
Error C2065 'geo2': undeclared identifier TestClasstypedef TestClasstypedef.cpp 63
我發現如果Geometry2::GetAnotherPoint()在內部定義為like Geometry2::GetAPoint(),問題就徹底解決了。
誰能幫我找出我的錯誤?先感謝您!
uj5u.com熱心網友回復:
問題是這是Geometry2<type>::Point一個依賴限定名。此外,此依賴名稱是一種型別,因此您需要將其告知編譯器,您可以通過添加關鍵字typenamebefore來做到這一點Geometry2<type>::Point。所以修改后的代碼如下:
template<class type>
typename Geometry2<type>::Point Geometry2<type>::GetAnotherPoint()//note the keyword typename here
{
Point test;
return test;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/427999.html
下一篇:#include帶有模板的遞回
