我有我打电话MyList
一个动态的基于阵列的类,看起来如下:模板参数为
#ifndef MYLIST_H
#define MYLIST_H
#include <string>
#include <vector>
using namespace std;
template<class type>
class MyList
{
public:
MyList();
~MyList();
int size() const;
type at() const;
void remove();
void push_back(type);
private:
type* List;
int _size;
int _capacity;
const static int CAPACITY = 80;
};
#endif
我也有我打电话User
,我想另一个类将MyList
的实例包含为私有数据成员。用户看起来是这样的:
#ifndef USER_H
#define USER_H
#include "mylist.h"
#include <string>
#include <vector>
using namespace std;
class User
{
public:
User();
~User();
private:
int id;
string name;
int year;
int zip;
MyList <int> friends;
};
#endif
当我尝试编译我得到一个错误在我user.cpp
文件:
未定义参考
MyList::Mylist()
我觉得这很奇怪,因为MyList
完全与user.cpp
无关,其中只包含我的User构造函数和析构函数。
你有没有实现构造函数? – 0x499602D2 2013-02-10 14:44:22
实例化它们时,类模板的定义必须可用。您无法像使用非模板类一样在源文件中定义模板。将定义移动到头文件中,或者从头文件中包含定义。 – mfontanini 2013-02-10 14:46:00
[为什么模板只能在头文件中实现?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Mat 2013-02-10 14:46:57