C ++ - 为什么我们应该在类定义之外定义纯虚拟析构函数? [英] C++ -- why should we define the pure virtual destructor outside the class definition?

查看:149
本文介绍了C ++ - 为什么我们应该在类定义之外定义纯虚拟析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Object {
public:
...
virtual〜Object()= 0;
...
};

Object ::〜Object(){} //我们应该总是定义纯虚拟析构函数吗?问题:我们是否应该在类定义之外定义纯虚拟析构函数?


$ b

$ b

换句话说,这是我们不应该定义任何虚函数inline的原因?



谢谢

解决方案

您可以内联定义虚函数。您不能内联定义纯虚拟函数。



根本不允许使用以下语法变体:

  virtual〜Foo()= 0 {} 
virtual〜Foo(){} = 0;

但这是完全有效的:

  virtual〜Foo(){} 

虚拟析构函数如果你打算实例化它或子类,ref 12.4 / 7:


析构函数可以被声明为virtual
)或纯虚拟(10.4);如果在程序中创建了该类的任何
对象或任何派生的
类,则应定义
析构函数。如果一个
类有一个虚拟的
析构函数的基类,它的析构函数(不管是
用户还是隐含声明)都是
virtual。



class Object {
public:
  ...
  virtual ~Object() = 0;
  ...
};

Object::~Object() {} // Should we always define the pure virtual destructor outside?

Question: Should we always define the pure virtual destructor outside the class definition?

In other words, it is the reason that we should not define any virtual function inline?

Thank you

解决方案

You can define virtual functions inline. You cannot define pure virtual functions inline.

The following syntax variants are simply not permitted:

virtual ~Foo() = 0 { }
virtual ~Foo() { } = 0;

But this is fully valid:

virtual ~Foo() { }

You must define a pure virtual destructor if you intend to instantiate it or subclasses, ref 12.4/7:

A destructor can be declared virtual (10.3) or pure virtual (10.4); if any objects of that class or any derived class are created in the program, the destructor shall be defined. If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly- declared) is virtual.

这篇关于C ++ - 为什么我们应该在类定义之外定义纯虚拟析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆