c++ - 在命名空间中定义模板类成员函数?

标签 c++

我环顾四周,试图找到这个问题的答案。是否可以在 cpp 文件内的命名空间中定义模板类的成员函数?当我尝试执行此操作时出现错误。

这是我尝试编译的两个文件。

ArrayList.hpp

     template<typename T>
     class ArrayList{
          ArrayList();
          ~ArrayList();
     }

ArrayList.cpp

    #include "ArrayList.hpp"

    namespace{

        template<typename T>
        ArrayList<T>::ArrayList(){

         /* function body goes here */

        }

        ArrayList<T>::~ArrayList(){

         /* function body goes here */

        }

编译器错误

 error: cannot define or
  redeclare 'ArrayList<T>' here because namespace '' does not enclose
  namespace 'ArrayList'
  ArrayList<T>::ArrayList()

最佳答案

您需要在定义其成员函数的同一命名空间中声明您的类。

您缺少 template<typename T>在你的析构函数之前。

namespace ANamespace
{

    template<typename T>
    class ArrayList
    {
        ArrayList();
        ~ArrayList();
    };

    template<typename T>
    ArrayList<T>::ArrayList()
    {

        /* function body goes here */

    }

    template<typename T>
    ArrayList<T>::~ArrayList()
    {

        /* function body goes here */

    }
}

关于c++ - 在命名空间中定义模板类成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837670/

相关文章:

c++ - 段错误,但不在 valgrind 或 gdb 中

c++ - 双指针 (int**) 和双括号从二维数组中获取值

c++ - directx 9 网格重叠 c++

c++ - MSBuild 2019 忽略 INCLUDE 环境变量

c++ - 基类函数被调用两次

c++ - 使用 Array 填充 List<> 得到错误的数字

c++ - 如何将 Qt 代码分解成单独的部分?

c++ - 来自加权 Delaunay 三角剖分的 Alpha 形状

c++ - Qt 中的继承不允许我引用?

c++ - ASCII 和字符程序