缺少的vtable通常意味着第一个非内联虚拟成员函数没有定义

Apa*_*nti 9 c++ virtual-destructor

我很确定这个问题是重复的,但我的代码在这里有所不同,以下是我的代码.它失败了"未定义的符号"错误,不确定丢失了什么.

class Parent {
   public :
     virtual int func () = 0;
     virtual ~Parent();

 };


 class Child : public Parent {
     public :

     int data;
     Child (int k) {
        data = k;
      }
    int func() {   // virtual function
       cout<<"Returning square of 10\n";
        return 10*10;
    }

    void Display () {
    cout<<data<<"\n";

 }

 ~ Child() {

    cout<<"Overridden Parents Destructor \n";

 }
};



int main() {
  Child a(10);
 a.Display();

 }
Run Code Online (Sandbox Code Playgroud)

以下是编译时的O/P.

Undefined symbols for architecture x86_64:
  "Parent::~Parent()", referenced from:
      Child::~Child() in inher-4b1311.o
  "typeinfo for Parent", referenced from:
      typeinfo for Child in inher-4b1311.o
  "vtable for Parent", referenced from:
      Parent::Parent() in inher-4b1311.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
Run Code Online (Sandbox Code Playgroud)

Chr*_*ckl 15

Parent::~Parent() 没有定义.

您可以将定义直接放入类定义中:

class Parent {
   public :
     virtual int func () = 0;
     virtual ~Parent() {};
 };
Run Code Online (Sandbox Code Playgroud)

或者单独定义它.或者,从C++ 11开始,写virtual ~Parent() = default;.

无论如何,析构函数需要一个定义.

  • 这里可以完全避免析构函数吗? (3认同)
  • @Olshansk:如果你想在某个时候构建它,则不是。如果它是可构造的,那么它一定是可破坏的。“虚拟”不会改变这一点。 (2认同)

Cos*_*h66 5

为了帮助以这种方式寻求帮助的其他人,“注意:缺少 vtable 通常意味着第一个非内联虚拟成员函数没有定义。”

在我的情况下,错误是由缺失 = 0 引起的;在虚拟定义的末尾。确保所有适当的虚拟定义都 = 0; 在末尾。

virtual HRESULT function(int testInput) = 0;
Run Code Online (Sandbox Code Playgroud)

希望这可以节省一些时间。

  • “确保所有的虚拟定义在最后都有= 0;”我很抱歉,但是= 0基本上是说这个虚拟函数是纯虚拟的,这反过来会将who类变成抽象类,有时我们的情况并非如此想。可以存在具有非纯虚函数的类。这个答案绝对是错误的 (3认同)