从.h中定义.cpp中的模板化函数(获取错误)

Bob*_*ohn 3 c++

头文件dlist.h的一部分定义为:

#ifndef __DLIST_H__
#define __DLIST_H__
#include <iostream>

class emptyList {};

template <typename T>
class Dlist {
 public:
    bool isEmpty() const;

 private:
    struct node {
    node   *next;
    node   *prev;
    T      *o;
    };

    node   *first; // The pointer to the first node (NULL if none)
    node   *last;  // The pointer to the last node (NULL if none)
};

#include "dlist.cpp"
#endif
Run Code Online (Sandbox Code Playgroud)

当我创建这样的dlist.cpp文件时:

#include "dlist.h"

template <typename T>
bool Dlist<T>::isEmpty() const
{
    return !first and !last;
}
Run Code Online (Sandbox Code Playgroud)

我在第4行收到错误消息:重新定义'bool Dlist :: isEmpty()const'

如果我删除了#include "dlist.h"我在第4行得到错误:在'<'标记之前的预期初始化程序

这里有什么帮助?有什么我做错了,不允许我从dlist.h文件中定义我的函数吗?谢谢.

jua*_*nza 7

您必须将类模板的成员函数的实现放在头文件或标头包含的文件中.编译器需要访问此代码才能实例化任何给定类型的模板T.

在你的情况下,问题似乎是你包括标题,.cpp反之亦然.如果你真的想在单独的文件中保留声明和实现,我建议将实现的后缀从.cpp其他东西改为,例如.icpp.某些构建系统可能会尝试使用.cpp后缀从任何内容编译目标文件,这也会导致错误.

  1. #include "dlist.h"从中移除dlist.cpp.
  2. (可选)重命名dlist.cppdlist.icpp.为什么?因为许多构建系统会自动编译.cpp以目标文件结尾的任何文件.许多程序员都认为.cpp文件被编译成目标文件.
  3. (仅在第2步中采用)包括重新命名dlist.icppdlist.h,如目前用于完成dlis.cpp.