单文件程序的未定义vtable

时间:2014-07-21 14:14:05

标签: c++ gcc functor

我写了以下最小的'sandbox'函数代码。

#include<cstdio>

struct Functor {
    virtual void operator() ();
    virtual ~Functor() {}
};

template<class Class, class FPtr>
struct FunctorImpl : Functor {
    FunctorImpl( Class const *_obj, FPtr _fptr ) : obj(_obj), fptr(_fptr) {}
    virtual void operator() () { (obj->*fptr)(); }
    virtual ~FunctorImpl() {}
protected:
    Class const *obj;
    FPtr fptr;
};

template<class Class, class FPtr>
FunctorImpl<Class,FPtr> *make_Functor( Class const *obj, FPtr fptr ) {
    return new FunctorImpl<Class,FPtr>(obj,fptr);
}

struct FOO {
    void bar() const { printf("1\n"); }
    void bar2() const { printf("2\n"); }
};

int main()
{
    FOO f;
    Functor* f1 = make_Functor( &f, &FOO::bar );
    Functor* f2 = make_Functor( &f, &FOO::bar2 );
    (*f1)();
    (*f2)();
}

然而,在编译时我得到了错误(使用gcc(GCC)4.8.3 20140624(Red Hat 4.8.3-1))

/tmp/cc4ayCAU.o: In function `Functor::~Functor()':
functor.cpp:(.text._ZN7FunctorD2Ev[_ZN7FunctorD5Ev]+0x13): undefined reference to `vtable for Functor'
/tmp/cc4ayCAU.o: In function `Functor::Functor()':
functor.cpp:(.text._ZN7FunctorC2Ev[_ZN7FunctorC5Ev]+0xf): undefined reference to `vtable for Functor'
/tmp/cc4ayCAU.o:(.rodata._ZTI11FunctorImplI3FOOMS0_KFvvEE[_ZTI11FunctorImplI3FOOMS0_KFvvEE]+0x10): undefined reference to `typeinfo for Functor'

如果只编译一个文件,这怎么可能?这个问题的解决方案是什么?

1 个答案:

答案 0 :(得分:3)

非抽象的虚函数(=0)需要一个正文,即使它们从未被调用过。要么为Functor::operator()提供虚拟身体,要么将其作为抽象函数。