没有主体的虚拟方法 [英] Virtual methods without body

查看:96
本文介绍了没有主体的虚拟方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在看抽象类中的一些代码:

I was looking at some code in an abstract class:

public virtual void CountX(){}

public virtual void DoCalculation() { ...code}

如果不是强制性地在派生类型中重写抽象类,为什么应该在抽象类中声明一个空的虚方法?

Why should I declare an empty virtual method in an abstract class if it is not mandatory to override it in derived types?

推荐答案

正如@Adam告诉您的,在很多情况下,这是有道理的.当您创建一个抽象类时,是因为您想为所有派生自该类的类创建一个公共接口.但是,在这种继承级别,您将没有足够的信息来为该方法创建有效的代码.

As @Adam told you, there are many cases in which it makes sense. When you create an abstract class, it's because you want to create a common interface for all classes deriving from that one; however, at that level of inheritance you won't have enough information to be able to create working code for that method.

例如,如果使用 getArea()方法创建类 Figure ,则将无法编写将正确计算出所有数字的区域.您必须等待为矩形圆形(均来自 Figure 派生)编写代码,才能编写代码为他们工作的代码.

For example, if you create the class Figure, with the getArea() method, you won't be able to write code that is going to correctly calculate the area for all figures. You'll have to wait to write the code for Rectangle, or Circle (both deriving from Figure), in order to be able to write working code for them.

这篇关于没有主体的虚拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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