对 vtable 和继承的 C++ 未定义引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9406580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Undefined Reference to vtable and inheritance
提问by rjmarques
File A.h
档案啊
#ifndef A_H_
#define A_H_
class A {
public:
virtual ~A();
virtual void doWork();
};
#endif
File Child.h
文件 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
和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.
编译器说有一个对 vtable for 的未定义引用A
。我尝试了很多不同的东西,但都没有奏效。
My objective is for class A
to be an Interface, and to seperate implementation code from headers.
我的目标是让类A
成为一个接口,并将实现代码与头文件分开。
回答by Alok Save
Why the error & how to resolve it?
为什么会出现错误以及如何解决?
You need to provide definitionsfor all virtual functions in class A
. Only pure virtual functions are allowed to have no definitions.
您需要提供的定义为所有虚拟功能class A
。只允许纯虚函数没有定义。
i.e: In class A
both the methods:
即:在class A
这两种方法中:
virtual ~A();
virtual void doWork();
should be defined(should have a body)
应该被定义(应该有一个身体)
e.g.:
例如:
A.cpp
A.cpp
void A::doWork()
{
}
A::~A()
{
}
Caveat:
If you want your class A
to act as an interface(a.k.a Abstract classin C++) then you should make the method pure virtual.
警告:
如果您希望自己class A
充当接口(又名C++ 中的抽象类),那么您应该使该方法成为纯虚拟的。
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.
回答by Mahesh
My objective is for A to be an Interface, and to seperate implementation code from headers.
我的目标是让 A 成为一个接口,并将实现代码与头文件分开。
In that case, make the member function as pure virtual in class A.
在这种情况下,将 A 类中的成员函数设为纯虚函数。
class A {
// ...
virtual void doWork() = 0;
};
回答by ArchZombie0x Ryan P. Nicholl
Make sure to delete any "*.gch" files if none of the other responses help you.
如果其他回复都没有帮助您,请确保删除任何“*.gch”文件。