使用C# 定义一个人员类 CPerson,包括数据成员:姓名、编号、性别和用于输入/输出的成员函数。在此基础上派生出学生类Cstudent(增-加成绩)和教师类CTeacher(增加教龄),并实现对学生和教师信息的输入/输出。
时间: 2024-10-13 07:06:41 浏览: 70
在C#中,我们可以首先定义一个基础的`CPerson`类,然后基于这个类创建两个派生类`CStudent`和`CTeacher`。这里是一个简单的示例:
```csharp
// 定义基础人员类 CPerson
public class CPerson
{
public string Name { get; set; }
public int ID { get; set; }
public char Gender { get; set; }
// 构造函数
public CPerson(string name, int id, char gender)
{
Name = name;
ID = id;
Gender = gender;
}
// 输入输出成员函数
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}, ID: {ID}, Gender: {Gender}");
}
}
// 派生学生类 CStudent
public class CStudent : CPerson
{
public double Grade { get; set; }
public CStudent(string name, int id, char gender, double grade)
: base(name, id, gender)
{
Grade = grade;
}
// 增加成绩功能
public void UpdateGrade(double newGrade)
{
Grade = newGrade;
}
// 输入输出成员函数扩展
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Grade: {Grade}");
}
}
// 派生教师类 CTeacher
public class CTeacher : CPerson
{
public int YearsOfTeaching { get; set; }
public CTeacher(string name, int id, char gender, int yearsOfTeaching)
: base(name, id, gender)
{
YearsOfTeaching = yearsOfTeaching;
}
// 增加教龄功能
public void UpdateYearsOfTeaching(int newYears)
{
YearsOfTeaching = newYears;
}
// 输入输出成员函数扩展
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"Years of Teaching: {YearsOfTeaching}");
}
}
```
现在你可以实例化这些类并显示他们的信息:
```csharp
public static void Main(string[] args)
{
CStudent student = new CStudent("张三", 1001, 'M', 90.5);
student.UpdateGrade(95);
student.DisplayInfo();
CTeacher teacher = new CTeacher("李四", 2001, 'F', 10);
teacher.UpdateYearsOfTeaching(15);
teacher.DisplayInfo();
}
```
阅读全文