何时将C ++中的函数标记为虚拟? [英] When to mark a function in C++ as a virtual?

查看:102
本文介绍了何时将C ++中的函数标记为虚拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于对方法的静态绑定的C ++性质,这会影响多态调用。

Because of C++ nature of static-binding for methods, this affects the polymorphic calls.

从维基百科:


虽然这种分派机制所涉及的开销较低,但
对于语言
设计为目标的某些应用程序领域仍然是重要的。为此,C ++的
设计器Bjarne Stroustrup选择了动态调度可选和
非默认。只有使用virtual关键字声明的函数将根据对象的运行时类型调度
;其他函数
将根据对象的静态类型分派。

Although the overhead involved in this dispatch mechanism is low, it may still be significant for some application areas that the language was designed to target. For this reason, Bjarne Stroustrup, the designer of C++, elected to make dynamic dispatch optional and non-default. Only functions declared with the virtual keyword will be dispatched based on the runtime type of the object; other functions will be dispatched based on the object's static type.

所以代码:

Polygon* p = new Triangle;
p->area();

在Child类中覆盖的父类中的code>非虚拟函数,上面的代码将调用父类的方法,这可能不是开发人员所期望的。 (感谢我介绍的静态绑定)

provided that area() is a non-virtual function in Parent class that is overridden in the Child class, the code above will call the Parent's class method which might not be expected by the developer. (thanks to the static-binding I've introduced)

因此,如果我想写一个类供其他人使用我使我所有的函数都是虚拟的,这样的以前的代码如预期运行

推荐答案

是你的类的函数被重写的运行时多态性你应该标记为 virtual ,而不是如果你不打算这样。

The simple answer is if you intend functions of your class to be overridden for runtime polymorphism you should mark them as virtual, and not if you don't intend so.

不要标记你的函数 virtual 只是因为你觉得它赋予额外的灵活性,而是想到你的设计和暴露一个接口的目的。例如:如果你的类不是被设计为继承的,那么使你的成员函数虚拟将是误导。一个很好的例子是标准库容器,它们不是被继承的,因此它们没有虚拟析构函数。

Don't mark your functions virtual just because you feel it imparts additional flexibility, rather think of your design and purpose of exposing an interface. For ex: If your class is not designed to be inherited then making your member functions virtual will be misleading. A good example of this is Standard Library containers,which are not meant to be inherited and hence they do not have virtual destructors.

有没有原因,标记所有的成员函数虚拟,引用一些性能惩罚,非POD类类型等等,但如果你真的想要你的类是意图运行时overidding那是它的目的及其所谓的缺陷。

There are n no of reasons why not to mark all your member functions virtual, to quote some performance penalties, non-POD class type and so on, but if you really intent that your class is intended for run time overidding then that is the purpose of it and its about and over the so-called deficiencies.

这篇关于何时将C ++中的函数标记为虚拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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