什么时候适合使用虚方法? [英] When is it appropriate to use virtual methods?

查看:62
本文介绍了什么时候适合使用虚方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道虚方法允许派生类覆盖从基类继承的方法.什么时候使用虚方法合适/不合适?并不总是知道一个类是否会被子类化.一切都应该是虚拟的,只是以防万一"?还是会导致大量开销?

I understand that virtual methods allow a derived class to override methods inherited from a base class. When is it appropriate/inappropriate to use virtual methods? It's not always known whether or not a class will be sub classed. Should everything be made virtual, just "in case?" Or will that cause significant overhead?

推荐答案

当你设计一个类时,你应该很清楚它是否代表一个接口(在这种情况下,你将适当的可重写方法和析构函数标记为虚拟)或者它旨在按原样使用,可能与其他对象组合或组合.

When you design a class you should have a pretty good idea as to whether it represents an interface (in which case you mark the appropriate overrideable methods and destructor virtual) OR it's intended to be used as-is, possibly composing or composed with other objects.

换句话说,您对课程的意图应该是您的指南.将所有东西都虚拟化通常是矫枉过正,有时还会在哪些方法旨在支持运行时多态性方面产生误导.

In other words your intent for the class should be your guide. Making everything virtual is often overkill and sometimes misleading regarding which methods are intended to support runtime polymorphism.

这篇关于什么时候适合使用虚方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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