带虚成员的模板类:链接器错误

Template class with virtual member: linker error

本文关键字:链接 错误 成员      更新时间:2023-10-16

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

使其成为一个纯虚函数