为什么当你创建一个带参数的默认参数的构造函数走开 [英] Why does the default parameterless constructor go away when you create one with parameters

查看:156
本文介绍了为什么当你创建一个带参数的默认参数的构造函数走开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#,C ++和Java,当你创建一个构造函数取的参数,默认参数的人去了。我一直只是接受了这个事实,但现在我已经开始想知道为什么。

In C#, C++ and Java, when you create a constructor taking parameters, the default parameterless one goes away. I have always just accepted this fact, but now I've started wondering why.

什么是对这种行为的原因是什么?难道只是一个安全措施/猜说:如果你已经创建了自己的构造函数,你的可能的不想要这个隐式单游逛?
或者它有技术上的原因,使得它不可能编译器添加一个一旦你创建了自己的构造?

What is the reason for this behavior? Is it just a "safety measure/guess" saying "If you've created a constructor of your own, you probably don't want this implicit one hanging around"? Or does it have a technical reason that makes it impossible for the compiler to add one once you have created a constructor yourself?

推荐答案

有没有理由,编译器不能添加构造函数,如果你添加你自己的 - 编译器可以做pretty多为所欲为!但是,你要看看什么最有意义的:

There's no reason that the compiler couldn't add the constructor if you've added your own - the compiler could do pretty much whatever it wants! However, you have to look at what makes most sense:


  • 如果我没有定义的任何的构造函数的非静态类,我很可能希望能够实例化类。为了允许,编译器的必须的补充参数的构造函数,这将有没有影响,但允许实例化。这意味着我不必包括我的code一个空的构造只是为了工作。

  • 如果我定义我自己的构造函数,尤其是带有参数的话,我极有可能必须在创建类执行我自己的逻辑。如果编译器创建在这种情况下一个空的,无参数的构造函数,它会允许某人的跳过的我写的逻辑,这可能会导致我的code打破所有多种方式。如果我想在这种情况下,一个默认的空构造,我必须这么说,明确地

  • If I haven't defined any constructor for a non-static class, I most likely want to be able to instantiate that class. In order to allow that, the compiler must add a parameterless constructor, which will have no effect but to allow instantiation. This means that I don't have to include an empty constructor in my code just to make it work.
  • If I've defined a constructor of my own, especially one with parameters, then I most likely have logic of my own that must be executed on creating the class. If the compiler were to create an empty, parameterless constructor in this case, it would allow someone to skip the logic that I had written, which might lead to my code breaking in all number of ways. If I want a default empty constructor in this case, I need to say so explicitly.

因此​​,在每一种情况下,你可以看到,当前的编译器的行为是最有​​意义的$ P $而言pserving的的可能意图code的

So, in each case, you can see that the behaviour of current compilers makes the most sense in terms of preserving the likely intent of the code.

这篇关于为什么当你创建一个带参数的默认参数的构造函数走开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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