我是否还需要在子类方法上指定 virtual ?
以前可能有人问过这个问题,但我找不到类似的问题。
考虑以下类层次结构:
class BritneySpears
{
public:
virtual ~BritneySpears();
};
class Daughter1 : public BritneySpears
{
public:
virtual ~Daughter1(); // Virtual specifier
};
class Daughter2 : public BritneySpears
{
public:
~Daughter2(); // No virtual specifier
};
Daughter1
和 Daughter2
类之间有区别吗?
在子类析构函数/方法上指定/不指定virtual
会产生什么后果?
This has probably been asked before on SO, but I was unable to find a similar question.
Consider the following class hierarchy:
class BritneySpears
{
public:
virtual ~BritneySpears();
};
class Daughter1 : public BritneySpears
{
public:
virtual ~Daughter1(); // Virtual specifier
};
class Daughter2 : public BritneySpears
{
public:
~Daughter2(); // No virtual specifier
};
Is there a difference between Daughter1
and Daughter2
classes ?
What are the consequences of specifying/not specifying virtual
on a sub-class destructor/method ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,从技术上讲,您不需要指定
虚拟
。如果基本成员函数是虚拟的,那么 C++ 将自动将匹配的重写成员函数设为虚拟。但是,您应该将它们标记为
override
,这确保它是virtual
,并且它覆盖基类中的成员函数。毕竟,该方法是虚拟的,它使您的代码更加清晰,更容易被其他开发人员遵循。注意:在 C++11 之前,您可以将重写成员函数设为
virtual
,因为override
尚不可用。No you technically do not need to specify
virtual
. If the base member function is virtual then C++ will automatically make the matching override member functionvirtual
.However you should be marking them
override
, which ensures that it'svirtual
, and also that it overrides a member function in the base class. The method isvirtual
after all, and it makes your code much clearer and easier to follow by other developers.Note: prior to C++11, you could make the overriding member function just
virtual
, sinceoverride
isn't available yet.您不需要它,但标记它可能会让您的代码更清晰。
- C++ 常见问题解答 - 我的析构函数何时应该是虚拟的?
You do not need it, but marking it so may make your code clearer.
- C++ FAQ - When should my destructor be virtual?
无论您是否在子类中指定它,都会在派生方法重写中自动选择 Virtual。
主要后果是,如果没有在子类中指定 virtual,则很难从子类定义中看出该方法实际上是 virtual 的。因此,我总是在父类和子类中指定 virtual。
Virtual is automatically picked up on derived method overrides regardless of whether you specify it in the child class.
The main consequence is that without specifying virtual in the child it's harder to see from the child class definition that the method is in fact virtual. For this reason I always specify virtual in both parent and child classes.