模板巢狀類別名作為函式返回型別,可能會提示的編譯錯誤
阿新 • • 發佈:2018-11-25
模板巢狀類別名作為函式返回型別,可能會提示的編譯錯誤
1 #include <iostream>
2 using namespace std;
3
4 template<typename ElementType>
5 class B
6 {
7 public:
8
9 /*樹的結點的資料結構*/
10 class A
11 { 12 13 }; 14 typedef A* Aptr; 15 16 /*取指向根節點的指標*/ 17 Aptr getRoot(); 18 19 protected: 20 Aptr root; //指向根節點的指標 21 22 }; 23 24 /*取指向根節點的指標*/ 25 template<typename ElementType> 26 B<ElementType>:: Aptr B<ElementType>::getRoot() 27 { 28 return root; 29 } 30 31 int main() 32 { 33 34 35 }
報錯提示為:
1>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(26): warning C4346: “B<ElementType>::Aptr”: 依賴名稱不是型別
1> 用“typename”為字首來表示型別
1>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(26): error C2143: 語法錯誤 : 缺少“;”(在“B<ElementType>::getRoot”的前面)
1>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(29): error C2509: “getRoot”: 成員函式沒有在“B<ElementType>”中宣告
1>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(29): fatal error C1903: 無法從以前的錯誤中恢復;正在停止編譯
若是把函式返回型別前面的類名作用域去掉,變為:
Aptr B<ElementType>::getRoot()
則報錯提示為:
>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(26): error C2143: 語法錯誤 : 缺少“;”(在“B<ElementType>::getRoot”的前面)
1>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(29): error C2509: “getRoot”: 成員函式沒有在“B<ElementType>”中宣告
1>e:\c++\common\consoleapplication28\consoleapplication28\源1.cpp(29): fatal error C1903: 無法從以前的錯誤中恢復;正在停止編譯
解決辦法是:
法一:將函式定義移到類內
法二:將巢狀類移到類外
1 #include <iostream>
2 using namespace std;
3 /*樹的結點的資料結構*/
4 class A
5 {
6
7 };
8 typedef A* Aptr;
9
10 template<typename ElementType>
11 class B 12 { 13 public: 14 15 16 17 /*取指向根節點的指標*/ 18 Aptr getRoot(); 19 20 protected: 21 Aptr root; //指向根節點的指標 22 23 }; 24 25 /*取指向根節點的指標*/ 26 template<typename ElementType> 27 Aptr B<ElementType>::getRoot() 28 { 29 return root; 30 } 31 32 int main() 33 { 34 35 36 }