代码如下:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Teacher t1 = new Teacher("许大虾", 23, "[email protected]", 10000); 6 Student s1 = new Student("许大虾", 23, "[email protected]", "100001"); 7 } 8 9 } 10 class Person//基类 11 { 12 13 public Person(string name,int age,string email) 14 { 15 16 this.Name = name; 17 this.Age = age; 18 this.Email = email; 19 } 20 public string Name { get; set; } 21 public int Age { get; set; } 22 public string Email { get; set; } 23 } 24 class Teacher : Person //派生类 25 { 28 public Teacher(string name, int age, string email,double salary) 29 { 30 this.Name = name; 31 this.Age = age; 32 this.Email = email; 33 this.Salary = salary; 34 } 35 public double Salary { get; set; } 36 } 37 class Student : Person//派生类 38 { 39 public Student(string name, int age, string email,string sno) 40 { 41 this.Name = name; 42 this.Age = age; 43 this.Email = email; 44 this.SNo = sno; 45 } 46 public string SNo { get; set; } 47 }
创建了Person父类,再让Student[子类]和Teacher[子类]继承Person类,同时分别在两个子类中各自添加一个构造函数。这时在父类也添加一个有参数的构造函数。编译生成后,发现产生了如下错误:
问题分析:
1.构造函数无法被继承
2.由于在创建子类对象的时候,一定会调用子类的构造函数,而任何一个子类构造函数默认情况下都会去调用父类的无参构造函数,所以当父类中没有无参构造函数时就出错了。
解决方法:
a.在父类中增加一个无参构造函数
b.在子类中指定子类的构造函数调用父类中没有参数的那个构造函数
代码变更:
a方案,直接在Person类添加一个无参构造函数
Public Person(){}
b方案,在子类中通过base()来指定调用父类[Person]的构造函数
class Teacher : Person { public Teacher(string name, int age, string email,double salary) :base(name,age,email) { //this.Name = name; //this.Age = age; //this.Email = email; this.Salary = salary; } public double Salary { get; set; } }
这里你会发现我把以下代码给注释掉了,原因是刚已经通过base()来手动调用父类的构造函数,而在父类中已经把这三个属性赋值了,所以就没必要再写一遍了
//this.Name = name; //this.Age = age; //this.Email = email;
这里需要注意的执行顺序是先调用父类的构造函数,然后再执行子类自己的构造函数
时间: 2024-11-01 10:20:09