文件 A.h
#ifndef A_H_#define A_H_A类{上市:虚拟 ~A();虚空 doWork();};#万一
文件 Child.h
#ifndef CHILD_H_#define CHILD_H_#include "A.h"类孩子:公共 A {私人的:整数 x,y;上市:孩子();~孩子();void doWork();};#万一
和 Child.cpp
#include "Child.h"孩子::孩子(){x = 5;}子::~子(){...}void Child::doWork(){...};
编译器说 A
有一个对 vtable 的未定义引用.我尝试了很多不同的东西,但都没有奏效.
我的目标是让 A
类成为一个接口,并将实现代码与标头分开.
为什么会报错&如何解决?
您需要提供定义 用于 A 类
中的所有虚函数.只允许纯虚函数没有定义.
即:在 class A
两个方法:
虚拟~A();虚空 doWork();
应该被定义(应该有一个主体)
例如:
A.cpp
void A::doWork(){}A::~A(){}
<小时>
警告:
如果您希望 class A
充当接口(又名 抽象类(在 C++ 中),那么您应该使该方法纯虚拟.
virtual void doWork() = 0;
<小时>
好书:
虚拟表"是什么意思外部未解决?
在构建 C++ 时,链接器说我的构造函数、析构函数或虚拟表未定义.>
File A.h
#ifndef A_H_
#define A_H_
class A {
public:
virtual ~A();
virtual void doWork();
};
#endif
File Child.h
#ifndef CHILD_H_
#define CHILD_H_
#include "A.h"
class Child: public A {
private:
int x,y;
public:
Child();
~Child();
void doWork();
};
#endif
And Child.cpp
#include "Child.h"
Child::Child(){
x = 5;
}
Child::~Child(){...}
void Child::doWork(){...};
The compiler says that there is a undefined reference to vtable for A
.
I have tried lots of different things and yet none have worked.
My objective is for class A
to be an Interface, and to seperate implementation code from headers.
Why the error & how to resolve it?
You need to provide definitions for all virtual functions in class A
. Only pure virtual functions are allowed to have no definitions.
i.e: In class A
both the methods:
virtual ~A();
virtual void doWork();
should be defined(should have a body)
e.g.:
A.cpp
void A::doWork()
{
}
A::~A()
{
}
Caveat:
If you want your class A
to act as an interface(a.k.a Abstract class in C++) then you should make the method pure virtual.
virtual void doWork() = 0;
Good Read:
What does it mean that the "virtual table" is an unresolved external?
When building C++, the linker says my constructors, destructors or virtual tables are undefined.
这篇关于C++ 对 vtable 和继承的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!