如何将数组传递给模板函数?

时间:2014-10-18 06:27:58

标签: c++ arrays templates

在我的主要内容中,我从模板类创建一个对象,然后调用我的排序方法(模板方法) 但是它在我的main.obj文件中出错。

错误:

LNK2019: unresolved external symbol "public: void __thiscall SelectionSort<int [0]>::IterativeSort(int * const,unsigned int)" ............

致电主要:

SelectionSort<int[]> smallArraySort;
smallArraySort.IterativeSort(smallArray, smallSize);

头文件:SelectionSort.h

template <class T>
class SelectionSort
{
    public:
        void IterativeSort(T data, unsigned int size);
        void RecursiveSort(T data, unsigned int size);

};

排序代码:SelectionSort.cpp

#include "SelectionSort.h"

template<class T>
void SelectionSort<T> ::IterativeSort(T data, unsigned int size)
{
    int temp = data[0];
    int greaterNum = 0


        for (unsigned int index = 0; index < size; index++)
    {
        for (unsigned int inner = index; inner < size; inner++)
        {
            if (temp>data[inner])
            {
                greaterNum = temp;
                temp = data[inner];
                data[inner] = greaterNum;

            }


        }
    }
}

1 个答案:

答案 0 :(得分:1)

这是因为您.cpp文件中实现模板的方法,在需要实例化时无法看到它们。一般来说,templates must be defined in a header file

要解决此问题,请将SelectionSort.cpp文件移至SelectionSort.h,以取消{{1}}文件。