C ++未定义对vtable和继承的引用 [英] C++ Undefined Reference to vtable and inheritance

查看:1107
本文介绍了C ++未定义对vtable和继承的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

档案啊

  #ifndef A_H_ 
#define A_H_

class A {
public:
virtual〜A();
virtual void doWork();
};

#endif

档案Child.h

  #ifndef CHILD_H_ 
#define CHILD_H_

#includeAh

:public A {
private:
int x,y;
public:
Child();
〜Child();
void doWork();
};
#endif

和Child.cpp

  #includeChild.h

Child :: Child(){
x = 5;
}

Child ::〜Child(){...}

void Child :: doWork(){...}

编译器说,有一个未定义的引用vtable A
我尝试了很多不同的东西,但都没有工作。



我的目标是类 A

解决方案

为什么会出现错误?如何解决?



您需要提供 A类中所有虚拟函数的定义和定义之间的区别定义 。只允许纯虚函数没有定义。



即: A类两种方法:

  virtual〜A(); 
virtual void doWork();

应定义(应有正文)



例如:



A.cpp

  void A :: doWork()
{
}
A ::〜A()
{
}






注意:

希望您的类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和继承的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆