虚拟成员函数的必要性
当基类和派生类中的每个函数具有相同的函数名称时,是否有必要将我的函数设置为虚拟函数,或者这只是更好编程的一部分?
when a have the same function name in a base class and a derived class with a different code for each function is it necessary to set my function as virtual or is it just part of better programming?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
根本没有必要将该方法设为虚拟方法。但是,如果您希望通过“后期绑定”调用它,即如果给定基指针,您希望调用派生方法,则它应该是虚拟的。
如果您不希望发生这种情况,通常是因为这些方法不相关,在这种情况下,您最好为派生类中的方法指定不同的名称。
It's not necessary at all to make the method virtual. However, it should be virtual if you want it to be called through "late binding", i.e. if, given a base pointer, you want the derived method to be called.
If you don't want that to happen, it's often because these methods are unrelated, in which case you better give the method in the derived class a different name.
虚拟函数的调用在运行时动态调度。这就是多态性的基础。
在基类中声明为虚函数的函数在子类中将隐式为虚函数。
Calls of virtual functions are dispatched dynamically at run-time. This is the basis of polymorphism.
A function that is declared as virtual in the base-class, will implicitly be virtual in sub-classes.
不,没有必要这样做。
事实上,何时声明虚拟、何时不声明是有效程序设计本身的一部分。
请参阅此处了解有关虚拟和纯虚函数。
No it's not necessary to do that.
In fact, when to declare virtual and when not to is part of effective program design itself.
Look here for more information on Virtual and Pure Virtual functions.
如果您希望使用基类指针指向派生类实例,并且函数具有相同的签名,那么您可能希望将函数设为虚拟,并将类析构函数设为虚拟。这样,如果有人有一个指向派生类型的父类指针,并且他们想要调用该函数,那么他们可能想要执行子类的版本(如果它与父类的版本不同)。
If you expect to use base class pointers to derived class instances, and the functions have the same signature, then you will probably want to make the function
virtual
, as well as make the class destructorsvirtual
. This way, if someone has a parent-class pointer to a derived type and they want to call that function, they will probably want to execute the child class' version if it's different from the parent's.请参阅 C++ 常见问题解答§继承 -
虚拟
函数。See C++ FAQ § Inheritance —
virtual
functions.