zoukankan      html  css  js  c++  java
  • 模板嵌套类别名作为函数返回类型,可能会提示的编译错误

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

     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++commonconsoleapplication28consoleapplication28源1.cpp(26): warning C4346: “B<ElementType>::Aptr”: 依赖名称不是类型
    1> 用“typename”为前缀来表示类型
    1>e:c++commonconsoleapplication28consoleapplication28源1.cpp(26): error C2143: 语法错误 : 缺少“;”(在“B<ElementType>::getRoot”的前面)
    1>e:c++commonconsoleapplication28consoleapplication28源1.cpp(29): error C2509: “getRoot”: 成员函数没有在“B<ElementType>”中声明
    1>e:c++commonconsoleapplication28consoleapplication28源1.cpp(29): fatal error C1903: 无法从以前的错误中恢复;正在停止编译

     

    若是把函数返回类型前面的类名作用域去掉,变为:

    Aptr B<ElementType>::getRoot()
    则报错提示为:

    >e:c++commonconsoleapplication28consoleapplication28源1.cpp(26): error C2143: 语法错误 : 缺少“;”(在“B<ElementType>::getRoot”的前面)
    1>e:c++commonconsoleapplication28consoleapplication28源1.cpp(29): error C2509: “getRoot”: 成员函数没有在“B<ElementType>”中声明
    1>e:c++commonconsoleapplication28consoleapplication28源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 }
  • 相关阅读:
    Discuz经典函数注释之authcode
    在delphi中,DLL加载时做初始化的Demo
    KERNEL32相关函数
    解析 png 图片的十六进制字符流
    delphi 获取硬盘序列号、cpu号、bios号、网卡号
    封装 INI 文件读写函数
    A窗口消失B窗口弹出
    delphi公用函数
    获取打开文件的PID
    C# cmd调用外部命令
  • 原文地址:https://www.cnblogs.com/hi3254014978/p/10014870.html
Copyright © 2011-2022 走看看