C++模板项目链接阶段报Gathering类gather方法未定义引用错误
错误根本原因
你遇到的链接错误是Gathering<ImplState, ImplRoute>::gather(ImplState const&)未定义引用,核心原因有两个:
Gathering模板类作为接口基类,定义了非纯虚的虚函数gather,但只提供了声明没有给出实现。C++要求所有非纯虚的虚函数必须有实现,哪怕子类完全重写了该函数,编译器生成基类虚函数表的时候也需要该函数的地址。- 你派生
ImplGathering时实例化了Gathering<ImplState, ImplRoute>这个模板类,构造其虚表时找不到gather函数的实现,因此链接器抛出未定义引用错误。
解决方案
推荐以下两种方案二选一即可:
方案1:将接口定义为纯虚函数(推荐)
因为Gathering本身就是纯接口类,不需要默认实现,直接将gather声明为纯虚函数即可,同时建议补充虚析构函数避免内存泄漏:
// 修改mctsimpl.hpp中的Gathering类定义 template <class T, class R> class Gathering { public: virtual R gather(const T&) = 0; // 加=0声明为纯虚函数 virtual ~Gathering() = default; // 补充虚析构函数 };
方案2:补充基类虚函数的默认实现
如果你的业务场景需要基类提供默认的gather逻辑,补充函数实现即可:
// 修改mctsimpl.hpp中的Gathering类定义 template <class T, class R> class Gathering { public: virtual R gather(const T&) { // 按业务需求编写默认实现即可,无需求可以返回默认构造的R对象 return R{}; } virtual ~Gathering() = default; };
修改后重新编译即可解决链接错误。
内容的提问来源于stack exchange,提问作者fields1631
相关产品推荐
相关产品推荐

