首页 > 解决方案 > virtual destrutors vs normal methods in C++

问题描述

Consider the following three programs in C++:

program 1

struct base{
  virtual ~base() =0;
};

struct derived: public base{
  ~derived();
};

derived::~derived(){}

int main(){}

program 2

struct base{
  virtual ~base() =0;
};

struct derived: public base{
  ~derived(){}
};

int main(){}

program 3

struct base{
  virtual void func() =0;
};

struct derived: public base{
  void func();
};

void derived::func(){}

int main(){}

The programs #2 and #3 compile and run fine however the first gives the following error:

Undefined symbols for architecture x86_64:
  "base::~base()", referenced from:
    derived::~derived() in main-d923b9.o
ls: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'd like to know why I am unable to define virtual destructors outside of the class definition however I am able to do it inside the class definition. Additionally I can define methods outside the class, just not destructors.

标签: c++destructorvirtual-functionsvirtual-destructor

解决方案


这是错误的

struct base{
  virtual ~base() =0;
};

因为base::~base没有定义。即使它已被声明为纯虚拟,也需要对其进行定义(在类之外,没有语法方法可以将函数声明为纯虚拟并内联定义),因此derived可以从中继承:

struct base
{
    virtual ~base() = 0;
};

base::~base() {}

我想知道为什么我无法在类定义之外定义虚拟析构函数

好吧,你可以:我刚刚做到了。


那么,为什么要实现一个~base已经声明为纯虚函数()?

由于derived继承自base,当一个类型的对象derived被破坏时,它必然调用base' 的析构函数。这就是继承的工作方式。从某种意义上说,derived::~derived需要与base::~base. 即使base::~base是纯虚拟的(意味着继承自的类base不是完整的类型,除非它定义了析构函数)它需要被定义以便~derived找到它并且链接器变得快乐。


推荐阅读