简体   繁体   English

未定义的vtable C ++

[英]Undefined vtable C++

#include <stdio.h>

class A {
public:
  virtual void print();
  A();
};

class B :public A {
public:
  void print();
  B();
};

class C :public B {
public:
  void print();
  C();
};

A::A(){
}

B::B(){
}

C::C(){
}

void B::print() {
  printf("From B\n");
}

void C::print() {
  printf("From C\n");
}

int main() {
  B* object = new C;
  object->print();

  return 0;
}

When I try to compile this C++ file, I get the following error. 当我尝试编译此C ++文件时,出现以下错误。 Can't figure out the reason. 无法找出原因。 I tried reading through similar undefined vtable questions on SO. 我尝试通读关于SO的类似未定义的vtable问题。

/tmp/ccpOkVJb.o: In function `A::A()':
test1.cpp:(.text+0xf): undefined reference to `vtable for A'
/tmp/ccpOkVJb.o:(.rodata._ZTI1B[_ZTI1B]+0x10): undefined reference to `typeinfo for A'
collect2: error: ld returned 1 exit status

If A::print() isn't meant to be implemented, declare it as pure: 如果不打算实现A::print() ,则将其声明为pure:

class A {
public:
  virtual void print() = 0;
  A();
};

Otherwise, implement it. 否则,请实施它。

You're declaring that there is supposed to be an A::print method implemented (you probably meant to make it pure virtual using = 0 ), but you're not implementing it. 您在声明应该实现一个A::print方法(您可能打算使用= 0将其变为纯虚拟),但是您没有实现它。

Since the first implemented virtual method makes the compiler instantiate the vtable and you've not implemented any in A, A's vtable is missing, leading to undefined reference to 'vtable for A' . 由于第一个实现的虚拟方法使编译器实例化vtable,而您尚未在A中实现任何方法,因此A的vtable丢失了,从而导致undefined reference to 'vtable for A'

You need to declare A::print() as pure virtual, or provide an implementation: 您需要将A::print()声明为纯虚拟的,或提供一个实现:

class A {
public:
  virtual void print()=0;
  A();
};

or 要么

class A {
public:
  virtual void print() {}
  A();
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM