繁体   English   中英

从基类继承

[英]inherit from a base class

可以说我有这堂课:

class foo
{
    public foo(Guid guid)
    {
        //some code here
    }

    public foo(Guid guid, bool myBool)
    {
        //some other code here
    }

    //Here I have a bunch of method/properties

    public void GenX(bool french, int width)
    {
        //my method implementation
    }
}

我有另一个类,它基本与foo相同,只是该方法public GenX(bool french, int width)和构造方法必须与foo的实现不同。

如果我以这种方式实现bar则编译器会抱怨: 'foo' does not contain a constructor that takes '0' arguments

class bar : foo
{
    public bar(Guid guid, bool myBool)
    {
        //some code here
    }

    new public void GenX(bool french, int width)
    {
        //my new method implementation
    }

    //I will be using the implementation of `foo` for the rest of the methods/properties
}

我究竟做错了什么? 这是做这种事情的正确方法吗?

如果这还不够清楚,我深表歉意,我将尽力使其更清楚

您必须确保调用了基本构造函数。

您可以这样做:

class bar : foo
{
    public bar(Guid g, bool b) : base (g)
    {
        // code here
    }
}

由于您尚未在代码中指定此名称,因此编译器将尝试默认/隐式调用默认构造函数。 但是,由于基类没有默认的构造函数(因为您已经指定了另一个构造函数,而未指定默认的构造函数),因此它无法调用它。 因此,您必须告诉编译器应该使用哪种基类的构造函数。

如果继承类中的构造函数所做的事情与基类中的构造函数完全不同,并且您不希望重用基类的构造函数,则可以执行以下操作:

class foo
{
   protected foo() 
   { 
      // default constructor which is protected, so not useable from the 'outside' 
   }

   public foo( Guid g ) 
   {}

   public foo( Guid g, bool b) : this(g) 
   {}

   public virtual void GenX() {}
}

class bar : foo
{
   public bar( Guid g, bool b) : base()
   {}

   public override void GenX() {}
}

尝试这个 :

class foo
{
    public foo(Guid guid)
    {
        //some code here
    }

    public foo(Guid guid, bool myBool,bool fooclass = true)
    {

        if (fooclass)
        {
            //some other code here
        }

    }

    //Here I have a bunch of method/properties

    public void GenX(bool french, int width)
    {
        //my method implementation
    }
}

class bar : foo
{
    public bar(Guid guid, bool myBool,bool barclass = true) : base(guid,myBool,false)
    {
        //some code here
    }

    new public void GenX(bool french, int width)
    {
        //my new method implementation
    }
}                                 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM