C++ Undefined Reference to vtable and inheritance(C++ 对 vtable 和继承的未定义引用)
问题描述
文件 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 和继承的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 对 vtable 和继承的未定义引用
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
