基本上,我想使用虚拟基类(C::doTask(double&)
)创建一个接口(A
),并让用户创建一个具体的类(B
)。在接口内部,我使用std :: bind来传递虚拟结构成员函数。在编译代码时,我得到了undefined reference to vtable for XXX
的错误。
任何建议都表示赞赏。谢谢!
这是头文件test.h
#include<functional>
#include<iostream>
typedef std::function<double(double const &)> MyFun;
// base class
struct A
{
double x;
// other parameters
A(){ x = 0.;};
virtual ~A();
virtual double fun(double const &x);
};
struct C
{
MyFun myfun;
void init(A &a)
{
using std::placeholders::_1;
myfun = std::bind( &A::fun, a, _1 );
}
double doTask(double x)
{
// do something
// call myfun
return 0.;
}
};
以下是main
文件test.cpp
#include<iostream>
#include "test.h"
// concrete class
struct B:A
{
// define some other parameters as members
double a,b;
B()
{
a=1.;
b=2.;
}
double fun(double const &x) override
{
return a+b+x;
}
};
int main()
{
B b;
C c;
c.init(b);
c.doTask(0.5);
return 0;
}
编译g++ --std=c++11 test.cpp
,我得到了:
/tmp/ccTmrVPi.o: In function `A::A()':
test.cpp:(.text._ZN1AC2Ev[_ZN1AC5Ev]+0x9): undefined reference to `vtable for A'
/tmp/ccTmrVPi.o: In function `std::_Head_base<0ul, A, false>::~_Head_base()':
test.cpp:(.text._ZNSt10_Head_baseILm0E1ALb0EED2Ev[_ZNSt10_Head_baseILm0E1ALb0EED5Ev]+0x14): undefined reference to `A::~A()'
/tmp/ccTmrVPi.o: In function `A::A(A const&)':
test.cpp:(.text._ZN1AC2ERKS_[_ZN1AC5ERKS_]+0xd): undefined reference to `vtable for A'
/tmp/ccTmrVPi.o: In function `B::~B()':
test.cpp:(.text._ZN1BD2Ev[_ZN1BD5Ev]+0x20): undefined reference to `A::~A()'
/tmp/ccTmrVPi.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference to `typeinfo for A'
collect2: error: ld returned 1 exit status