2017-04-11 74 views
-1

我想創建一個派生類,我收到每個構造函數的語法錯誤。構造函數的定義:接收「沒有參數給出」

沒有給定參數對應於「Parent.Parent(父)」的要求正式 參數「P」

這沒有任何意義,我。這是一個構造函數的定義,不是一個方法調用,我從來沒有看到過這個不是調用的東西。

namespace ConsoleApp1 
{ 

     public class Parent 
     { 
      public string Label; 

      public Parent(Parent p) 
      { 
       Label = p.Label; 
      } 
     } 

     public class Child : Parent 
     { 
      public string Label2; 

      public Child(Parent p) 
      { 
       Label = p.Label; 
      } 

      public Child(Child c) 
      { 
       Label = c.Label; 
       Label2 = c.Label2; 
      } 

      public Child(string blah, string blah2) 
      { 
       Label = blah; 
      } 
     } 
    class Program 
    { 
     static void Main(string[] args) 
     { 

     } 
    } 
} 
+0

今後,這將是最好減少您的問題到'[mcve'] - 在這種情況下,基類與參數的構造(理想的是普通型的,如'string')以及具有單個構造函數的派生類。將錯誤消息顯示爲文本而不是圖像... –

+0

我確實將錯誤消息顯示爲文本..... – TheColonel26

+0

因此,您不需要將它顯示爲圖像。該圖像實際上並沒有添加任何其他內容,只是顯示它是具有紅色小方格的類名 - 這是您剛纔可以輕易描述的。 –

回答

6

此:

public LabelImage(LabelImage source) 
{ 
    Label = source.Label; 
    image = new MagickImage(source.image); 
    fileinfo = source.fileinfo; 
} 

含蓄是這樣的:

public LabelImage(LabelImage source) : base() 
{ 
    Label = source.Label; 
    image = new MagickImage(source.image); 
    fileinfo = source.fileinfo; 
} 

注意base()部分,試圖調用無論是MyImageAndStuff參數的構造函數,或一個只擁有params陣列參數,或者只有一個可選參數。沒有這樣的構造函數存在,因此錯誤。

你可能想:你的所有其他構造

public LabelImage(LabelImage source) : base(source) 
{ 
    Label = source.Label; 
    image = new MagickImage(source.image); 
    fileinfo = source.fileinfo; 
} 

...和類似的事情。要麼,要麼你需要添加一個無參數構造函數MyImageAndStuff。看起來很奇怪,你不能創建MyImageAndStuff的實例,而不是已經有的實例MyImageAndStuff - 雖然我猜source可能爲空。

+0

@Nabren是正確的,因爲基類沒有定義默認的構造函數。你給出了更詳細的答案,所以你可以得到答案。 – TheColonel26

1

由於MyImageAndStuff沒有無參數的構造函數或可以在沒有任何參數傳遞給它的構造函數的情況下解析,所以您需要在LabelImage中的所有派生構造函數中顯式調用MyImageAndStuff中的構造函數。例如:

public LabelImage(LabelImage source) 
    : base(source) 
+1

請注意,在描述編譯器爲您提供的構造函數時,術語「默認構造函數」通常用於C#規範中。在這種情況下,你的意思是「無參數構造函數」 - 但只有一個'params'數組參數或只有可選參數的構造函數也可以。 –

+0

@Jon Skeet,謝謝更新了答案 – Nabren

+0

儘管它還是不正確 - 如果只有'MyImageAndStuff(MyImageAndStuff source = null)'它不會有無參數的構造函數,但它會編譯。另一方面,修復這將使你的答案基本上是我的一個子集... –

相關問題