什么时候虚拟方法应该是纯粹的? [英] When should a virtual method be pure?

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

问题描述



如果一个基类将一个方法定义为虚拟的,但是我已经找到了一些我正在努力工作的代码,

 实现一个空体,因此不需要派生类来实现一个体。 virtual void AMethod1(){} // 1 
virtual void AMethod2(){assert(false);} // 2
virtual void AMethod3()= 0; // 3




  1. 目前的代码。

  2. Idea1:提醒使用者这个衍生物件尚未导入这个方法主体。

  3. Idea2:强制派生类别实现一个正文,不为空。

你认为什么是值得信赖的人?






Edit1:发布(并阅读答案)后,我意识到assert是错误的。

  virtual void AMethod3 = {throw(ENotImplemented)}; // 4 


解决方案

你的编码风格是。有些人认为你应该总是定义一个纯虚拟函数的接口,并从中导出所有具体的类。



其他更实用,更相信如果有一个好的默认实现,你可以添加到基类(选项1)。



第二个选项似乎是最不有用,因为它延迟检测,直到运行时。大多数程序员宁愿选择选项3中的编译错误。



像往常一样,C ++支持几种范例,你可以选择你喜欢的范例。


I have found some code that I am working on, and was wondering what the best design implementation is.

If a base class defines a method as virtual, but implements an empty body as well, thus not requiring the derived classes to implement a body, should it not be made pure instead?

virtual void AMethod1() {}                 // 1
virtual void AMethod2() {assert(false);}   // 2
virtual void AMethod3() = 0;               // 3

  1. Current code.
  2. Idea1: Alerts user that this derived object has not implemented this method body.
  3. Idea2: Forces derived classes to implement a body, empty or not.

What do you, the trusted amazing SO people, think?


Edit1: After posting (and reading answers), I realize that assert is bad!

virtual void AMethod3() = {throw (ENotImplemented)};               // 4

解决方案

It depends a bit on how "pure" your coding style is. Some people believe that you should always define an interface with pure virtual functions only and derive all concrete classes from that.

Others are more pragmatic and belive that if there is a good default implementation, you can add that to the base class (option 1).

The second option seems to be the least useful, as it delays detection until runtime. Most programmers would rather prefer a compilation error from option 3.

As usual, C++ supports several paradigms and you can choose the one you prefer.

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

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