2012-03-29 56 views
4

我最近發現沒有參數構造函數和多個參數構造函數不能輪流調用對方。這種限制的根本原因是什麼?有人可能會說,構造函數是資源初始化的地方。所以他們不能被遞歸調用。我想知道這是否唯一的原因。函數/方法/過程可以遞歸調用。爲什麼不是構造函數?構造函數調用自己

+2

有一個構造函數調用本身有效地創建一個無退出的無限循環。 – 2012-03-29 03:46:10

+1

不是。假設你在catch子句中添加recusive步驟,那不會導致無限循環。 – 2014-01-20 00:15:00

回答

5

答案在於一個事實,即調用另一個構造函數是任何構造的第一行,因此你如果條件打破遞歸的永遠不會被執行,因此堆棧溢出。

1

構造函數是不是要對象的初始化外顯式調用,因爲它在大多數(我猜的一切),語言的限制。相反,您可以創建一個額外的protected Init(...)成員函數並在構造函數中調用它。

1

你的語句構造函數不能調用其他的構造是不是真的對每個編程語言。至少我知道Java可以做到這一點,而C++不能。但是你可以通過編寫一個私有的__init函數輕鬆克服這個限制,讓所有的構造函數調用它。

+0

我的意思是輪流遞歸調用對方。我認爲Java會給這個編譯時錯誤。 – 2012-03-29 03:59:31

1

在所有語言中你所列出的對象包含有限的(並且通常短)的一組屬性。每個屬性可以包含遞歸結構(即列表),但它仍然由對象中的單個屬性表示。

我不認爲需要遞歸調用構造函數。這感覺就像一個奇怪的使用遞歸來初始化幾個衆所周知的屬性。

正如你所說,你可以調用非遞歸的方式構造在你所提到的一些語言共享代碼。

C#:Using Constructors

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

構造的主要目的是初始化特定類的所有的全局變量。

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.