2010-11-17 171 views
1

我有三個參數構造函數的恕我直言很奇怪的問題,當我嘗試運行程序時,Visual Studio只顯示了一個錯誤:「'Sort.HeapSort'不包含構造函數,它需要3個參數112 35「。C#構造函數的奇怪問題

namespace Sort 
{ 
    class HeapSort 
    { 
     private int[] A; 
     private int heapSize; 
     private int min; 
     private int max; 
     Random myRandom = new Random(); 

     HeapSort(int size, int min1, int max1) //this is the three argument constructor. 
     { 
      heapSize = size - 1; 
      min = min1; 
      max = max1; 
      A = new int[size]; 
     }  
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      int size = 30; 
      int min = 0; 
      int max = 100; 

      HeapSort myHeapSort = new HeapSort(size,min,max); //In this line is the bug 
     } 
    } 
} 
+1

你有沒有嘗試過公開構造函數? – 2010-11-17 16:36:06

+0

你能刪除無用的線路嗎?:) – ykatchou 2010-11-17 16:36:21

+0

也許你應該用適當的訪問修飾符來修飾你的類。公共,私人,保護等。 – StingyJack 2010-11-17 16:36:37

回答

9

由於您省略了訪問說明符,因此您的構造函數被聲明爲private。在構造函數定義之前添加public關鍵字。

+0

它的工作原理,謝謝:) – Konrad 2010-11-17 16:42:09

+0

你應該檢查更新/向下按鈕下面的方框接受他的答案,而不是編輯標題來標記它已解決。 – 2010-11-17 17:12:57

3

你需要指定你的構造爲public,正是如此:

public HeapSort(int size, int min1, int max1) 

編譯器允許你省略無障礙符,默認爲私有。國際海事組織的一句話,我希望會被廢除。

因此,由於您有一個私有構造函數,因此您的客戶端代碼不會「看見」它,編譯器會嘗試調用公共構造函數,這會自然導致您看到的錯誤。

+0

它的作品謝謝:) – Konrad 2010-11-17 16:42:33

2

你的構造函數不公開,它是私有的(你沒有包含任何修飾符,所以它默認爲私有的),因此調用代碼不能「看見」它。

變化:

HeapSort(int size, int min1, int max1) 

要:

public HeapSort(int size, int min1, int max1) 
1

您需要添加public到你的構造,否則它被認爲是private,因此從Main()內無法訪問。

1

帶有三個參數的構造函數沒有輔助功能修飾符,因此默認爲private

將聲明更改爲public HeapSort(int size, int min1, int max1),那麼您將很適合。

0

看起來你在構造函數之前缺少'public'關鍵字。

0

讓您的構造函數公開!

0

您的構造函數是私有的。它需要公開。