如果可以继承一个类,那么每个函数都应该是虚拟的吗? [英] If a class might be inherited, should every function be virtual?

查看:77
本文介绍了如果可以继承一个类,那么每个函数都应该是虚拟的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,一个编码器不知道其他编码器是否会继承他的类.他应该将该课程中的每个功能虚拟化吗?有什么缺点吗?还是根本不接受?

In C++, a coder doesn't know whether other coders will inherit his class. Should he make every function in that class virtual? Are there any drawbacks? Or is it just not acceptable at all?

推荐答案

在C ++中,仅当您打算多态使用该类时,才应使该类可继承.在C ++中处理多态对象的方式与处理其他对象的方式非常不同.您不倾向于将多态类放在堆栈上,也不要按值传递它们或从函数返回它们,因为这可能导致 slicing .多态对象倾向于堆分配,传递并通过指针或引用等返回.

In C++, you should only make a class inheritable from if you intend for it to be used polymorphically. The way that you treat polymorphic objects in C++ is very different from how you treat other objects. You don't tend to put polymorphic classes on the stack, or pass them by or return them from functions by value, since this can lead to slicing. Polymorphic objects tend to be heap-allocated, be passed around and returns by pointer or by reference, etc.

如果您设计一个不被继承的类,然后再从其继承,则会引起各种问题.如果析构函数未标记为虚拟,则无法通过基类指针删除该对象而不会引起未定义的行为.没有标记为 virtual 的成员函数,就不能在派生类中覆盖它们.

If you design a class to not be inherited from and then inherit from it, you cause all sorts of problems. If the destructor isn't marked virtual, you can't delete the object through a base class pointer without causing undefined behavior. Without the member functions marked virtual, they can't be overridden in a derived class.

作为C ++中的一般规则,在设计类时,请确定是否要继承该类.如果这样做,请标记相应的功能 virtual ,并为其提供一个 virtual 析构函数.您也可以禁用复制分配运算符以避免切片.同样,如果您希望该类不可继承,则不要给它们提供任何这些功能.在大多数情况下,从并非设计为要继承的类继承是一种逻辑错误,并且在大多数情况下,您通常想使用 composition 而不是继承来继承该类.达到这种效果.

As a general rule in C++, when you design the class, determine whether you want it be inherited from. If you do, mark the appropriate functions virtual and give it a virtual destructor. You might also disable the copy assignment operator to avoid slicing. Similarly, if you want the class not to be inheritable, don't give it any of these functions. In most cases it's a logic error to inherit from a class that wasn't designed to be inherited from, and most of the times you'd want to do this you can often use composition instead of inheritance to achieve this effect.

这篇关于如果可以继承一个类,那么每个函数都应该是虚拟的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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