C#-继承中的构造函数

父类
class Base{
    private int hp;   private int speed;
    public Base(int hp,int speed){
        this.hp=hp; this.speed=speed;
    }
    public Base(){Console.WriteLine("父类中构造函数");}
}
子类
class Child : Base
    {
        private int attack;
        //Ⅰ
        public Child() { Console.WriteLine("子类中的构造函数"); }
        //Ⅱ
        public Child(int attack):base()//->:base()可以不写,本来也会先调用父构,再调子构
        {
            this.attack= attack;
        }
        //Ⅲ
        public Child(int attack, int hp, int speed) : base(hp, speed)//调用父类2参构造函数,并使用Child中的参数值
        //将 : 前的hp,speed作为参数,调用适配的父构
        {
            this.attack= attack;
        }
        //Ⅳ
        //public Child(int attack,int hp,int speed):base()//调用父类无参构造函数
        //{
        // this.attack=attack;
        // base.hp=hp;  base.speed=speed;
        // }
        //Ⅲ和Ⅳ只能有一个存在,因为同名又同参
    }
调用

调用构造函数原则:先适配,若无,再调用默认无参构

Main()
{
    Child c1 = new Child();//=>调用顺序:父类无参构,子构无参构
    Child c2 = new Child(80);//=>调用顺序:父构无参构,子构1参构
    Child c3 = new Child(80, 100, 10);//=>调用顺序:父2参构,子构3参构
}
继承中的构造函数的特点
  1. 执行顺序:从老祖宗开始 依次一代一代向下执行。→先执行父类的构造函数,再执行子类的。

  2. 子类实例化时,默认自动调用父类的无参构造。如果父类无参构造被顶掉,会报错。

  3. 如果被顶掉。子类中就无法默认调用无参构造了

    解决方法: 1.始终保持声明一个无参构造 2.通过base关键字,调用指定父类的构造
    class Father
    {
        //public Father()
        //{

        //}

        public Father(int i)
        {
            Console.WriteLine("Father构造");
        }
    }
    class Son:Father
    {
        -----通过base调用指定父类构造-----
        public Son(int i) : base(i)//父类没有了无参构造,则指定一个父类的构造函数
        {
            Console.WriteLine("Son的一个参数的构造");
        }

        public Son(int i, string str):this(i)
        {
            Console.WriteLine("Son的两个参数的构造");
        }
    }
--------------------------------------
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("继承中的构造函数");

            MainPlayer mp = new MainPlayer();

            Son s = new Son(1,"123");
//执行顺序:Father(int i)->Son(int i)->Son(int i, string str)
        }
    }
}

C#-继承中的构造函数_第1张图片

你可能感兴趣的:(C#,c#)