为什么我会被虚拟和具体的课程"Undefined symbols ... typeinfo ... vtable"?

Why am I getting "Undefined symbols ... typeinfo ... vtable" with a virtual and concrete class?

本文关键字:Undefined symbols typeinfo vtable 虚拟 为什么      更新时间:2023-10-16

我正在重新学习C++(意思是:对我温柔一点!:)。我有一个具有抽象方法(step())的超类(Node),该方法必须在子类(TestNode)中实现。它编译时没有错误,也没有任何警告,但链接它会导致:

bash-3.2$ g++ -Wall -o ./bin/t1 src/t1.cpp
Undefined symbols for architecture x86_64:
  "typeinfo for test::Node", referenced from:
      typeinfo for test::TestNode in t1-9f6e93.o
  "vtable for test::Node", referenced from:
      test::Node::Node() in t1-9f6e93.o
  NOTE: a missing vtable usually means the first non-inline virtual member function has no definition.
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

据我所知,我已经定义了"第一个非内联虚拟成员函数"(即TestNode::step())。

我仔细阅读了错误消息,我阅读了这里的博客文章,并查看了许多其他SO文章(未定义的符号"vtable for…"answers"typeinfo for…"?,如何找到类的未定义虚拟函数,以及c++缺失的vtable错误),但我觉得离启蒙并不近。

我错过了什么?

这是整个程序。

#include <stdio.h>
namespace test {
  class Node {
  public:
    virtual Node& step(int count);
  };
  class TestNode : public Node { 
  public:
    TestNode();
    ~TestNode();
    TestNode& step(int count);
  };
  TestNode::TestNode() { }
  TestNode::~TestNode() { }
  TestNode& TestNode::step(int count) {
    printf("count = %dn", count);
    return *this;
  }
} // namespace test    
int main() {
  return 0;
}

问题是您没有提供Node::step()的实现。如果您真的希望Node没有步骤的实现,那么您应该使它成为一个纯虚拟函数Node::step(int count) = 0,从而使Node成为一个抽象类(您不能直接实例化它)。否则,定义Node::步骤的实现。

据我所知,我已经定义了"第一个非内联虚拟成员函数"(即TestNode::step())。

您似乎混淆了定义和声明。基类中只有声明而没有定义,即实现。

您要么需要使它成为纯虚拟的,要么实现它,即使它只是一个空的{}。

class Node {
public:
    virtual Node& step(int count);
 };

快速解决方法可能是:

class Node {
public:
    virtual Node& step(int count) = 0;
                               // ^^^ making it pure virtual
 };

或:

class Node {
public:
    virtual Node& step(int count) { };
                               // ^^^ empty implementation for now
 };
相关文章: