c++ - 为什么虚拟函数在分配给 'new' 时不能未实现?

标签 c++ linker-errors language-lawyer virtual-functions

struct A
{
  virtual void foo();  // unused and unimplemented
  virtual void bar () {}
};

int main ()
{
  A obj;        // ok
  obj.bar();  // <-- added this edition
  A* pm = (A*)malloc(sizeof(A)); // ok
  A* pn = new A; // linker error
}

对于堆栈上的对象 it works fine .但是对于使用 new(不是 malloc)在堆上分配,它会给出链接器错误:

undefined reference to `vtable for A'

最佳答案

因为 malloc 不调用(或在这种情况下尝试调用)A 的构造函数,而 new 调用。

此代码编译并记录 GCC 链接器错误发生的位置:

#include <cstdlib>

struct A
{
  virtual void foo();  // unused and unimplemented
  virtual void bar () {}
};

int main ()
{
  A obj;        // linker error
  A* pm = (A*) malloc(sizeof(A)); // ok
  A* pn = new A; // linker error
}

关于c++ - 为什么虚拟函数在分配给 'new' 时不能未实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6230376/

相关文章:

c++ - 链接硬编码函数指针

c++ - 检测移除打开的串口设备(Qt/Windows)

c++ - 左值引用和右值引用之间的重载决议

c++ - 指针如何将字符串作为其值?

python - 错误: command 'c++' failed with exit status 1

ios - 如何将 ObjCMongoDb 集成到 iOS 应用程序中?

C++ 链接器错误 : undefined references only on optimized build

c++ - 私有(private)数据成员类型的静态成员

c++ - 全局分配函数和 const void*

c - 为什么所有指向结构的指针都必须具有相同的大小?