

class Father { public Father(int a) { }//构造函数重载,顶掉了无参的默认构造函数 } class Son : Father //这里会报错,子类实例化会默认调用父类的无参构造函数,但无参构造已经被顶掉了. { }//在Father类里面添加无参构造函数就好了
所以继承里的构造函数里面无参构造函数非常重要.代码报错有两种解决方法:
1.保持声明父类的无参构造;
2.用base指定调用父类的一个有参构造;
base是调用父类的指定构造,
this是调用当前类的指定重载构造
class Father { public Father(int a) { Console.WriteLine("一个参数的父类构造"); } } class Son : Father { public Son(int a) : base(a)//会调用父类一个参数的默认构造 { Console.WriteLine("一个参数的子类构造"); } public Son(int a, string str) : this(a)//会调用一个参数的子类构造, { Console.WriteLine("两个参数的子类构造"); } } internal class Program { static void Main(string[] args) { Son son = new Son(1,"1"); } }
看运行结果:

