我在同一目录下有以下三个文件:
citysim.cpp
#include "utils.h"
using namespace std;
int main()
{
City *c;
c = new City();
Graph<City *> g;
g.addVertex(c);
}
utils.h
#include <iostream>
#include <map>
#include <vector>
using namespace std;
class City {
public:
City() {}
private:
string name;
};
template <typename Tkey>
class Graph {
public:
Graph() {}
void addVertex(Tkey);
private:
vector<Tkey> v;
vector< vector<int> > e;
map<Tkey, int> key_map;
};
utils.cpp
#include "utils.h"
template <typename Tkey>
void Graph<Tkey>::addVertex(Tkey vertex)
{
v.push_back(vertex);
}
我真的很困惑为什么下面的编译序列会产生所示的结果:
test> g++ -c citysim.cpp
test> g++ -c utils.cpp
test> g++ -o citysim citysim.o utils.o
citysim.o: In function `main':
citysim.cpp:(.text+0x4a): undefined reference to `Graph<City*>::addVertex(City*)'
collect2: ld returned 1 exit status
欢迎任何想法或见解!
最佳答案
在头文件中定义模板类的所有内容,而不是在 cpp 文件中。而不是让你的 utils.cpp 在你的头文件中有这样的一切:
template <typename Tkey>
class Graph {
public:
Graph() {}
void addVertex(Tkey vertex)
{
v.push_back(vertex);
}
private:
vector<Tkey> v;
vector< vector<int> > e;
map<Tkey, int> key_map;
};
Here是FAQ中的相关阅读...
编辑: (但是您也可以稍后像在头文件中的 cpp 中那样定义它...)
关于c++ - 无法链接 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9878680/