2017-04-11 81 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)'它不会有无参数的构造函数,但它会编译。另一方面,修复这将使你的答案基本上是我的一个子集... –

相关问题