无法解析未定义的参考

Unable to resolve Undefined reference

本文关键字:参考 未定义      更新时间:2023-10-16

我在功能模板中遇到问题,我试图在Functions.cpp中实例化函数。但是这样做后,它给了我汇编错误。以下是我遇到的错误。如果有人能够提供帮助,将非常感谢它!谢谢!

错误

Functions.cpp:81:15: error: template-id ‘remove<int>’ for ‘int 
CS150::remove(int*, int*, int*)’ does n template declaration
template int remove<int>(int *first, int*last,  int* val);
             ^~~~~~~~~~~
Functions.cpp:56:5: note: candidate is: template<class T> T* 
CS150::remove(T*, T*, T*)
T* remove(T *first, T *last,  T* val)
   ^~~~~~

function.cpp

template <typename T> 
T* remove(T *first, T *last,  T* val)
{
    T result = first;
    while (first!=last) 
    {
        if (!(*first == val)) 
        {
        *result = *first;
        ++result;
        }
        ++first;
    }
    return result;
}
template int remove<int>(int *first, int*last,  int* val);

functions.h

template <typename T> 
T* remove(T *first, T *last, const T& val);

驱动程序文件

static void TestRemove1(void)
{
    cout << "***** Remove1 *****" << endl;
    int i1[] = { 5, -7, 4, 10, -21, 15, 9 };
    int size = sizeof(i1) / sizeof(int);
    CS150::display(i1, i1 + size);
    int item = -1;
    int * newend = CS150::remove(i1, i1 + size, item);
    cout << "remove " << item << ", new list: ";
    CS150::display(i1, newend);
}
static void TestRemove2(void)
{
    cout << "***** Remove2 *****" << endl;
    int i1[] = {5, -7, 4, 10, -7, 15, 9};
    int size = sizeof(i1) / sizeof(int);
    CS150::display(i1, i1 + size);
    int item = -7;
    int *newend = CS150::remove(i1, i1 + size,  item);
    cout << "remove " << item << ", new list: ";
    CS150::display(i1, newend);
}

您不需要template关键字。以下可能会起作用(我仍然不确定为什么您根本需要此行):

int remove<int>(int *first, int*last,  int* val);

通过编写remove<int>实例化模板,因此它不再是模板。

您的模板函数签名表示它返回T*,但是您的功能定义和实例返回Tint)。您需要使它们匹配。