3

可能重复:
为什么模板只能在头文件中实现?
与字符串 (GCC)
C++ 模板一起使用时对函数模板的未定义引用,未定义引用

我觉得我缺少链接 C++ 项目的东西。我不确定问题出在标头源中还是包含在内,因此我制作了一个最小的代码示例来演示它。

主模块 minmain.cpp:

 #include <stdio.h>
 #include <vector>
 #include <string>
 #include "nodemin.h"

 using namespace std;

 int main()
 {
     // Blist libs are included
     Node<int>* ndNew = ndNew->Root(2);

     return 0;
 }

头文件 nodemin.h:

 #ifndef NODETEMP_H_
 #define NODETEMP_H_

 using namespace std;

 template<class T>
 class Node
 {
 protected:

    Node* m_ndFather;
    vector<Node*> m_vecSons;
    T m_Content;

    Node(Node* ndFather, T Content);

 public:

     // Creates a node to serve as a root
         static  Node<T>* Root(T RootTitle);
 };

 #endif

节点模块 nodemin.cpp:

 #include <iostream>
 #include <string.h>
 #include <vector>
 #include "nodemin.h"

 using namespace std;

 template <class T>
 Node<T>::Node(Node* ndFather, T Content)
 {
    this->m_ndFather = ndFather;
    this->m_Content = Content;
 }

 template <class T>
 Node<T>* Node<T>::Root(T RootTitle) { return(new Node(0, RootTitle)); }

编译行:

 #g++ -Wall -g mainmin.cpp nodemin.cpp

输出:

 /tmp/ccMI0eNd.o: In function `main':
 /home/******/projects/.../src/Node/mainmin.cpp:11: undefined reference to`Node<int>::Root(int)'
 collect2: error: ld returned 1 exit status

我尝试编译成对象,但链接仍然失败。

4

1 回答 1

0

添加template class Node<int>;到 nodemin.cpp:

#include <iostream>
#include <string.h>
#include <vector>
#include "nodemin.h"

using namespace std;

template <class T>
Node<T>::Node(Node* ndFather, T Content)
{
   this->m_ndFather = ndFather;
   this->m_Content = Content;
}

template <class T>
Node<T>* Node<T>::Root(T RootTitle) { return(new Node(0, RootTitle)); }

template class Node<int>;
于 2012-06-02T18:27:51.753 回答