c++:使用标头时未定义对vtable的引用,但不能没有

c++: undefined reference to vtable when using header but not without

本文关键字:引用 vtable 但不能 未定义 c++      更新时间:2023-10-16

我有一个接口,我想用interface中的函数创建一个header,用.cpp实现这个头中的函数。但当尝试此操作时,我总是在Testt.h文件中遇到问题undefined reference to 'vtable for Test'

我正在eclipse中做一个相当大的项目,所以我把问题归结为几个小类。

ITestAdapter.h:

#ifndef ITESTADAPTER_H_
#define ITESTADAPTER_H_
class TestAdapter {
public:
virtual int test() = 0;
};
#endif /* ITESTADAPTER_H_ */

测试h:

#ifndef TESTT_H_
#define TESTT_H_
#include "ITestAdapter.h"
class Test: public TestAdapter{
public:
virtual int test();
};
#endif /* TESTT_H_ */

Testt.cpp:

#include "Testt.h"
int test() {
return 0;
}

Test_main.cpp:

#include <iostream>
#include "Testt.h"
using namespace std;
int main() {
Test t;
int i = t.test();
cout << i << endl;
return 0;
}

如果我根本不使用Testt.h,而是在Testt.cpp中实现接口,并用我的主方法将Testt.cpp(我想避免的)包含在文件中,那么它可以正常工作。

Testt.cpp(已修改):

#include "ITestAdapter.h"
class Test: public TestAdapter {
public:
int test() {
    return 0;
}
};

所以我不明白为什么如果我使用标头(我认为这是更好的解决方案),它就不起作用。

我希望我能解释清楚我的问题是什么。如果不能,请问。

您正在Testt.cpp中定义一个非成员函数int test()。您需要定义int Test::test():

int Test::test()
{// ^^^^
  return 0;
}

对X的未定义引用意味着链接器找不到已声明的X的定义。

您声明Test具有成员函数int test(),但此

int test() {
   return 0;
}

定义了一个自由函数。

你需要

int Test::test() {
    return 0;
}

undefined reference to 'vtable for Test'"测试有点令人困惑。这通常意味着您忘记定义类的第一个虚拟函数。