c++ - 使用模板的构造函数链接器错误

标签 c++ templates constructor

我刚开始使用模板。

我想创建一个链表类来存储类型(可以是一个对象)的地址。这是我的项目的布局:

linkedlist.h
node.h
node.cpp
linkedlist.cpp
main.cpp

Node.h

template <class Type> struct Node
{
public:
    Node<Type>();
    Node<Type>(Type* x = 0, Node* pNext = 0);
    Type* data;
    Node* next;
};

Node.cpp

#include "node.h"

template<class Type> Node<Type>::Node()
{
    next = 0;
    data = 0;
}
template<class Type> Node<Type>::Node(Type* item, Node* ptrNext)
{
    next = ptrNext;
    data = item;
}

链表.h

#include "node.h"

template <class Type> class LinkedList
{
private:
    Node<Type>* root;

public:
    LinkedList<Type>();
    ~LinkedList<Type>();
    void insert(Type*);
    void remove(Type*);
};

链表.cpp

#include "linkedlist.h"

template <class Type> LinkedList<Type>::LinkedList()
{
    root = 0;
}

template <class Type> LinkedList<Type>::~LinkedList()
{
    Node* p;
    while(p = root)
    {
        root = p->next;
        delete p;
    }
}
// many more....

在 main.cpp 中,我有以下内容:

int main()
{
    int *ptrA, *ptrB;
    int a = 100, b = 10;

    ptrA = &a;
    ptrB = &b;

    LinkedList<int>myList;
    myList.insert(ptrA);
    return 0;
}

并且编译器抛出了链接器错误:

1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::~LinkedList<int>(void)" (??1?$LinkedList@H@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall LinkedList<int>::insert(int *)" (?insert@?$LinkedList@H@@QAEXPAH@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall LinkedList<int>::LinkedList<int>(void)" (??0?$LinkedList@H@@QAE@XZ) referenced in function _main

尝试的解决方案:

我改为调用 LinkedListmyList()。这可以解决链接器错误,但我将无法调用任何成员函数。

如果我输入 (),myList.insert(ptrA) 会说“错误:表达式必须有一个类类型”。

很明显这是行不通的。

有什么问题?我认为整个实现都有问题....

感谢您的宝贵时间。

最佳答案

将内容从 linkedlist.cpp .. 移动到 linkedlist.h

因为它声明了一个“用于制作代码的模板”,所以在您为编译器提供您想要使用的类型之前,机器代码实际上并不存在。

比如只要所有的模板代码对编译器可见,你就去:LinkedList<int>myList编译器创建了构成整数链表的实体实类。在您的情况下,编译器看不到模板代码,因此无法生成机器代码。


在 C++11 中你可以说 'extern template': http://en.wikipedia.org/wiki/C%2B%2B11#Extern_template

在头文件中,然后在您的 linkeList.cpp 文件中实现“int”版本。当它尝试使用它时,它将在 main.cpp 中可用。

这提供了编译器不必在使用模板的每个 .cpp 文件中生成机器代码的优势,并使编译速度更快。

它也可以在 c++98 中完成..但它有点棘手,而且据我所知不是 100% 可移植的..更容易在任何地方生成代码。这是 gnu gcc 的一个很好的介绍:http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html

关于c++ - 使用模板的构造函数链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8569983/

相关文章:

c++ - 如何使用模板专门化模板?

c++ - 将类型 T 的多态包装器转换为类型 U?

javascript - 了解使用 'Object.create()' 而不是 'new' 关键字创建原型(prototype)对象

c++ - 复制构造函数(深复制)c++

c++ - Objective-C 与 C++ 成员初始化

c++ - 将信息从一个正在运行的函数发送到另一个

c++ - 将 cout 语句转换为 fwrite 函数

c++ - 使用 C 调用约定调用函数模板特化

c++ - 数字生成 C++

c++ - 访问 C++ 变量时如何解析其内容?