构造函数调用自己

我最近发现没有参数构造函数和多个参数构造函数不会轮流调用彼此。 这种限制的根本原因是什么? 有些人可能会说构造函数是资源初始化的地方。 所以不能递归调用它们。 我想知道这是否是唯一的原因。 函数/方法/过程可以递归调用。 为什么不是施工人员?

答案在于,对另一个构造函数的调用是任何构造函数的第一行,因此您的if条件将永远不会被执行,因此堆栈溢出。

构造函数的主要目的是初始化特定类中描述的所有全局变量。

For Example: public class Addition(){ int value1; int value2; public Addition(){ // default constructor a=10; b=10; } public Addition(int a, int b){ this(); // constructors having parameters , overloaded constructor value1=a; value2=b; } } public class Main(){ public static void main(){ Addition addition = new Addition(); //or Addition addition = new Addition(15,15); } } Here, if you want to make instance of the class you can either make instance by calling default constructor or by calling constructor having parameters. So the constructors are overloaded and not overridden. If you want to call another constructor, that can only be done be putting either this() or super() in the first line of the constructor. But this is not prefferable. 

构造函数不打算在对象初始化之外显式调用,因为它在大多数(我猜所有)语言中受到限制。 相反,您可以创建一个额外的protected Init(...)成员函数,并在构造函数中调用它。

您的构造函数无法调用其他构造函数的语句对于每种编程语言都不适用。 至少我知道Java可以做到这一点,而C ++则不行。 但是您可以通过编写私有__init函数轻松克服此限制,并让所有构造函数调用它。

在所有语言中,您列出的对象包含有限(通常很短)的属性集。 每个属性都可以包含递归结构(即列表),但它仍然由对象中的单个属性表示。

我认为不需要递归调用构造函数。 感觉就像一个奇怪的使用递归来初始化几个众所周知的属性。

正如您所说,您可以以非递归方式调用构造函数,以您提到的某些语言共享代码。

C#: 使用构造函数

 public Employee(int weeklySalary, int numberOfWeeks) : this(weeklySalary * numberOfWeeks) { }