c++ - 类所需的模板参数

标签 c++

我有一个基于动态数组的类,我称之为 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()

我觉得这很奇怪,因为 MyListuser.cpp 完全无关,它只包含我的 User 构造函数和析构函数。

最佳答案

确保将模板类的声明和定义都写入 header (在 header 而不是 .cpp 文件中定义 MyList)

关于c++ - 类所需的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14798870/

相关文章:

c++ - 类构造函数和数组

c++ - 如何在 C++ 中初始化线程局部变量?

c++ - 使用 double 比 float 快吗?

c++ - 调整 sfml 应用程序的窗口大小

c++ - 序列点和评估顺序(预增量)

c++ - move 语义以从缓冲区获取数据的所有权?

c++ - 如何将静态控件背景设置为对话框背景?

c++ - 将包含指针的数据插入 vector

OMNET++ 中的 C++ 编码

c++ - 如何用 C++ 编写通用排序函数?