我有一个基于动态数组的类,我称之为 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
实例作为私有(private)数据成员。用户看起来像这样:
#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
文件中出现错误:
undefined reference to
MyList::Mylist()
我觉得这很奇怪,因为 MyList
与 user.cpp
完全无关,它只包含我的 User 构造函数和析构函数。
最佳答案
确保将模板类的声明和定义都写入 header (在 header 而不是 .cpp 文件中定义 MyList)
关于c++ - 类所需的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14798870/