模板嵌套类别名作为函数返回类型,可能会提示的编译错误

模板嵌套类别名作为函数返回类型,可能会提示的编译错误

 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 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值