【问题标题】:how to call a base class non default constructor from the instantion of the derived class?如何从派生类的实例中调用基类非默认构造函数?
【发布时间】:2013-03-28 18:39:06
【问题描述】:

我有一个基类和派生类。基类有 2 个构造函数,如下所示。

    class A
{
    public A()
    {
        Console.WriteLine("I AM BASE class");
    }

    public A(int x)
    {
        Console.WriteLine("base : parameter 1");
    }
}

class B : A
{
    public B()
    {
        Console.WriteLine("I AM DERIVED class");
    }
}

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        Console.ReadKey();
    }
}

输出是 I AM BASE CLASS 和 I AM DERIVED CLASS 我的要求是,当 B 被实例化时,应该调用基类的参数化构造函数而不是默认构造函数。 请告诉我如何实现这一目标?

【问题讨论】:

  • 可以在默认构造函数中添加base关键字。
  • 在这种情况下使用构造函数初始化列表。
  • 代码是问题是C#,不是C++
  • @Sean 它最初被标记为 C#,但 ismail baig 错误地将其重新标记为 C++(现在他/她自己修复了错误)

标签: c#


【解决方案1】:

在 B 的构造函数中使用初始化器列表

class B : A
{
    public B() : A(42)
    {
        Console.WriteLine("I AM DERIVED class");
    }
};

【讨论】:

    【解决方案2】:

    像这样编写B 构造函数:

     public B() : base(1)
     {
       Console.WriteLine("I AM DERIVED class");
     }
    

    注意:我已将问题标签更改为 C#,因为您提供的代码是 C#,而不是 C++。

    【讨论】:

    • 它被称为成员初始化列表
    【解决方案3】:
    class B : A
    {
        public B()
        {
            Console.WriteLine("I AM DERIVED class");
        }
        public B(int x)
        : A(x)
        {
            Console.WriteLine("I AM DERIVED class (with a parameter)");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 2017-02-10
      • 2016-07-19
      • 2020-12-12
      • 2011-05-03
      • 2018-07-16
      • 2018-07-21
      • 2014-03-26
      • 2011-09-27
      相关资源
      最近更新 更多