c++ - 如果我使用单独的 .cpp 和 .hpp 文件,则使用内部函数的未定义引用
问题描述
资源:
测试.hpp
template<class R>
class Base
{
public:
virtual R copy() = 0;
virtual ~Base() = default;
R test();
R testCallback();
};
class Derived: public Base<Derived>
{
public:
Derived()
{
}
Derived copy();
};
测试.cpp
#include "test.hpp"
template<class R>
R Base<R>::testCallback()
{
return R();
}
template<class R>
R Base<R>::test()
{
return testCallback();
}
Derived Derived::copy()
{
return Derived();
}
应用程序.cpp
#include "test.hpp"
int main(int argc, char const *argv[])
{
Derived a = Derived();
Derived b = a.test();
return 0;
}
对于应用程序编译,我使用:
g++ 源/test.cpp 源/app.cpp -o 测试
之后我得到了错误:
对 «Base::test()» 的未定义引用
如果我将所有代码从中剪切test.cpp
并放入app.cpp
. 如果我R test()
在头文件中标记为虚函数,它也可以工作。
为什么链接器看不到test()
实现函数?我做错了什么?
解决方案
推荐阅读
- reactjs - 如何在 React Native 中的抽屉导航组件中嵌套堆栈导航
- python - Selenium Pytest GitLab CI - pytest 问题
- php - 致命错误:未捕获的类型错误:count():参数 #1 ($var) 必须是 Countable|array 类型,在
- c# - Entity Framework 6 不能选择所有列,只能选择一个子集
- mocking - SoapUI:一次运行多个具有相同端口和路径的 Soap Mock 服务
- android - Android Lint 消息:更新到 Fragment 1.3.0 以在分析/检查代码中使用 ActivityResult API 错误
- laravel - Laravel 关系,需要建议
- python-3.x - 循环页面并将详细内容保存为 Python 中的数据框
- python - 我可以使用 spacy 在字符串中识别“问题词”(谁,如何,何时......)?
- javascript - 注销后如何清除浏览器缓存(内存/磁盘缓存)?