当没有其他构造函数时,是否有理由显式编写默认构造函数? [英] Is there a reason to explicitly code a default constructor when there are no other constructors?

查看:90
本文介绍了当没有其他构造函数时,是否有理由显式编写默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一个类中看到了这个构造函数:

I recently saw this constructor in a class:

public MyClass(){ }

没有其他构造函数。

这有什么理由吗? Java会自动创建一个默认构造函数,那么为什么要显式声明一个呢?或者这被认为是一种良好的做法,就像对单语句if语句使用大括号一样 - 如果稍后添加其他构造函数并且您忘记了没有默认值...?

Is there a reason for this? Java automatically creates a default constructor, so why would you declare one explicitly? Or is this considered good practice in the same way as using braces for single-statement if statements - in case other constructors are added later and you forget that you don't have a default...?

推荐答案

在这种情况下,你可能不会看到几个小点。

A couple minor points that aren't likely to be why you saw it in this case.


  • 它为您提供了设置断点的功能。

  • 您可以将其设为非公开

至于如果以后添加其他构造函数并且您忘记了没有默认值 - 这可能是一个原因,我想。但是如果添加了非默认构造函数,那么使用默认构造函数的任何代码都将无法编译,因此添加新构造函数的人通常也需要为默认的ctor添加一个defintion。

As far as "in case other constructors are added later and you forget that you don't have a default" - that might be a reason, I suppose. But if a non-default constructor were added, any code that used the default constructor would fail to compile, so the guy adding the new constrcutor would generally need to also add a defintion for the default ctor as well.

然后,我再也没想到定义空ctor有什么特别的伤害(虽然现在我输入了这个,我觉得有人可能会指出C ++的某个角落它可以咬你的地方)。

Then again, I can't think of any particular harm in having the empty ctor defined (though now that I've typed that, I get a feeling that someone might point out some corner of C++ where it could bite you).

这篇关于当没有其他构造函数时,是否有理由显式编写默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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