c++ - 具有虚拟成员 : linker error 的模板类

标签 c++ templates abstract-class template-specialization virtual-functions

<分区>

考虑以下代码。 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

clang 输出:

/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,因此链接器不知道该方法是抽象的,因此正在寻找不存在的函数体。

关于c++ - 具有虚拟成员 : linker error 的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40440302/

相关文章:

c++ - 重载 address-of 运算符的用例

java - java中模板类型的instanceof

java - Java 中的抽象对象比较

c++ - 有关模板和虚拟功能的问题

c++ - 双向链表 std::unique_ptr 类在删除节点时无法按预期工作

swift - ARKit – 光估计

c# - 关于重构为抽象类的基本问题

c++ - boost.proto + 从特定领域的表达式包装器中展开表达式

c++ - 启动默认电子邮件客户端以打开带有预选文件附件的 "send email"窗口

C++ 需要有关 OpenCV 教程中代码的帮助