编写一个控制台程序,在该程序中构造一个Person基类,再分别构造Student和Teacher派生类,要求具有不同的特征和行为,能通过静态成员自动记录由不同派生类创建的对象的人数。c#
时间: 2024-03-18 14:40:02 浏览: 21
好的,以下是C#语言的代码实现,满足您的要求:
```c#
using System;
class Person
{
protected string name;
protected int age;
public Person(string n, int a)
{
name = n;
age = a;
}
public virtual void Show()
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
}
public static int count;
}
class Student : Person
{
protected string major;
public Student(string n, int a, string m) : base(n, a)
{
major = m;
count++;
}
public override void Show()
{
Console.WriteLine("Type: Student");
base.Show();
Console.WriteLine("Major: " + major);
}
}
class Teacher : Person
{
protected string subject;
public Teacher(string n, int a, string s) : base(n, a)
{
subject = s;
count++;
}
public override void Show()
{
Console.WriteLine("Type: Teacher");
base.Show();
Console.WriteLine("Subject: " + subject);
}
}
class Program
{
static void Main(string[] args)
{
Person[] people = new Person[5];
people[0] = new Student("Tom", 20, "Computer Science");
people[1] = new Student("Jerry", 19, "Mathematics");
people[2] = new Teacher("Alice", 35, "English");
people[3] = new Teacher("Bob", 45, "Physics");
people[4] = new Student("Peter", 22, "Economics");
for (int i = 0; i < 5; i++)
{
people[i].Show();
Console.WriteLine();
}
Console.WriteLine("Number of people: " + Person.count);
Console.ReadKey();
}
}
```
这个程序中,我们定义了一个基类 `Person`,以及两个派生类 `Student` 和 `Teacher`。每个类都有一个 `Show()` 函数,用于显示对象的信息。`Person` 类还有一个静态成员变量 `count`,用于记录由不同派生类创建的对象的人数。在 `Student` 和 `Teacher` 构造函数中,我们将 `count` 加1,以便自动记录对象的数量。在 `Main()` 函数中,我们创建了5个对象,并通过对象数组调用它们的 `Show()` 函数。最后,我们输出了创建的对象数量。
希望这个程序能够满足您的要求!