2013-02-10 126 views
0

我有我打电话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构造函数和析构函数。

+2

你有没有实现构造函数? – 0x499602D2 2013-02-10 14:44:22

+3

实例化它们时,类模板的定义必须可用。您无法像使用非模板类一样在源文件中定义模板。将定义移动到头文件中,或者从头文件中包含定义。 – mfontanini 2013-02-10 14:46:00

+0

[为什么模板只能在头文件中实现?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Mat 2013-02-10 14:46:57

回答

1

确保你写这两个声明和模板类的定义到页眉(不是在.cpp文件中定义MYLIST在头)

+0

在头文件中声明模板类的格式是什么? – 2013-02-10 14:52:37

+0

@DanielHwang定义已经是声明。 – Potatoswatter 2013-02-10 14:53:21

+0

感谢您的快速响应,那么我应该添加到标题然后呢? – 2013-02-10 15:04:47

0

的原因是你没有提供MyClass<int>构造函数的定义。不幸的是,在C++中,你不能通过在头文件中声明方法并在实现中定义它们来划分模板类的定义。至少如果你想在其他模块中使用它。所以在你的情况下,用户类需要立即定义MyClass<int>::MyClass()。有两种方法可以做到这一点:

  1. (最简单的一个)提供到位的构造函数的定义权: MyClass() { ... }或MyClass.h类定义一样,后

  2. add方法的定义: template<class type> MyList<type>::MyList() { ... }