带虚成员的模板类:链接器错误
Template class with virtual member: linker error
考虑以下代码。A是一个抽象的泛型类;B既实现了它,又专门化了它。这段代码对我来说似乎是微不足道的正确,但由于某种原因,我最终得到了奇怪的链接器错误。
template<typename T>
class A {
public:
virtual void f();
};
class B : public A<int> {
public:
void f() {};
};
int main(int argc, char** argv) {
auto b = new B();
return 0;
}
gcc输出:
/tmp/ccXG2Z8A.o:(.rodata._ZTV1AIiE[_ZTV1AIiE]+0x10): undefined reference to `A<int>::foo()'
collect2: error: ld returned 1 exit status
叮当声输出:
/tmp/l2-2a09ab.o: In function `main':
l2.cpp:(.text+0x35): undefined reference to `operator new(unsigned long)'
/tmp/l2-2a09ab.o:(.rodata._ZTI1AIiE[_ZTI1AIiE]+0x0): undefined reference to `vtable for __cxxabiv1::__class_type_info'
/tmp/l2-2a09ab.o:(.rodata._ZTI1B[_ZTI1B]+0x0): undefined reference to `vtable for __cxxabiv1::__si_class_type_info'
/tmp/l2-2a09ab.o:(.rodata._ZTV1AIiE[_ZTV1AIiE]+0x10): undefined reference to `A<int>::foo()'
clang: error: linker command failed with exit code 1 (use -v to see invocation)
从gcc输出中,我假设您的函数名为foo
而不是f
。
问题是类A
不是抽象的,因为您没有这样声明它的方法。你可以这样做:
virtual void foo() = 0;
但是您忘记了= 0
,因此链接器不知道该方法是抽象的,因此正在寻找不存在的函数体。
A不是抽象类。你应该这样做:
virtual void f() = 0;
使其成为一个纯虚函数
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- Visual Studio mkl_link_tool.exe链接错误
- C++ 实现模板单例类时出现链接错误
- 使用类模板的方法链接错误
- MySQL C++连接器链接错误
- VS 2015 链接错误 无法构建依赖于 libcurl 的项目
- 运行 C++ 单元测试时LNK2005链接错误
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 链接错误,包括我创建的相同头文件 - C++
- 在Embarcadero C++ Builder中生成的DLL未解决的外部链接错误
- 使用标头保护的多个定义链接错误
- 链接错误:未定义对 stdscr 和 wgetch 的引用
- 使用 Vivek 的 Vcam / 捕获源过滤器构建/链接错误
- 升压program_options中的链接错误
- 使用 g++ 预处理器进行替换会导致链接错误
- 在调试配置中编译工作正常,但发布会给出链接错误
- 相邻矩阵设置链接错误
- 包含常量变量并包含在多个文件中的标头的链接错误
- C++链接错误,我理解但无法解决
- 是什么导致macOS Mojave上的GoogleTest链接错误