生成C++模板类时未解析的外部

Unresolved external when building C++ Template Class

本文关键字:外部 C++ 生成      更新时间:2023-10-16

我正在尝试构建一个BehaviourTree数据结构。"main"类是"BTNode",叶子(动作、命令或条件)是"BTLeaf"。因为我想让BTLeaf对我的实体执行一些操作,所以我把它做成了一个模板类,它接受一个对象和一个成员函数指针。

btnode.h:

#ifndef BTNODE_H
#define BTNODE_H
#include <QLinkedList>
class BTNode
{
public:
    BTNode();
    BTNode(QLinkedList<BTNode *> &children);
    ~BTNode();
    virtual bool execute() = 0;
protected:
    QLinkedList<BTNode*> _children;
};
#endif // BTNODE_H

btleaf.h:

#ifndef BTLEAF_H
#define BTLEAF_H
#include "btnode.h"
template <class T> class BTLeaf : public BTNode
{
public:
    BTLeaf(T* object, bool(T::*fpt)(void))
    { _object = object; _fpt=fpt; }
    /* Does not work either:
    BTLeaf(T* object, bool(T::*fpt)(void))
        : BTNode()
    { _object = object; _fpt=fpt; }
    */
    virtual bool execute()
    { return (_object->*_fpt)(); }
private:
    bool (T::*_fpt)(); //member function pointer
    T* _object;
};
#endif // BTLEAF_H

当我尝试构建解决方案(使用Qt Creator)时,我得到:

spider.obj:-1: error: LNK2019: unresolved external symbol "public: __thiscall BTNode::BTNode(void)" (??0BTNode@@QAE@XZ) referenced in function "public: __thiscall BTLeaf<class Spider>::BTLeaf<class Spider>(class Spider *,bool (__thiscall Spider::*)(void))"

你可以在我的代码中看到我尝试的解决方案被注释掉了。如果我删除public BTNode部分并"手动"使用btleaf,我会得到所需的结果。有什么想法吗?

编辑:我在Spider类中以这种方式(出于测试目的,暂时)创建BTLeaf可能毫无价值:

BTLeaf<Spider> test(this, &Spider::sayHello);
test.execute();

假设您声明的BTNode默认(无参数)构造函数没有在任何地方定义(至少,没有在链接器看到的任何地方定义)。