0

这很奇怪。当我包含一个 .h 文件 (GeneralSearch.h) 时,怎么可能会出错,但是当我包含 .cpp 文件 (GeneralSearch.cpp) 时,一切似乎都正常工作?

.h 文件

#ifndef GENERALSEARCH_H_
#define GENERALSEARCH_H_

#include "Problem.h"
#include "Node.h"

template <class T>
class GeneralSearch
{
public:

    const Node* treeSearch(const Problem &problem) const;
    const Node* graphSearch(const Problem &problem, T &fringe = T()) const;

private:
    void expand(const Node &node, const Problem &problem, list<const Node*> &out) const;
};

#endif

.cpp 文件

#include "GeneralSearch.h"
template <class T>
void GeneralSearch<T>::expand(const Node &node, const Problem &problem, list<const Node*> &out) const
{
...
}

template <typename T>
const Node* GeneralSearch<T>::treeSearch(const Problem &problem) const
{
...
}

template <typename T>
const Node* GeneralSearch<T>::graphSearch(const Problem &problem, T &fringe = T()) const
{
...
}

程序文件 - 工作

#include "GeneralSearch.cpp"
#include "DummyProblem.h"
#include "DepthFirstSearch.h"
#include <queue>

int main (int argc, char* argv[]){}

程序文件 - 不工作

#include "GeneralSearch.h"
#include "DummyProblem.h"
#include "DepthFirstSearch.h"
#include <queue>

int main (int argc, char* argv[]){}
4

1 回答 1

1

链接器尝试在链接时查找未解析名称的定义。在第二种情况下,链接器无法找到 GeneralSearch 类的成员函数的定义,因此您会收到错误消息。

于 2012-05-05T07:34:14.333 回答