定义人类Person, 包含姓名、性别两个字段及用于初始化这两个字段的构造函数。然后,从Person类派生出一个学生类Student,为其扩展出一个学号字段,同时为学生类创建构造函数来初始化其三个字段,要求其中从父类中继承的字段由父类的构造函数负责初始化。请利用静态字段的知识在学生类中增加表示男生和女生数的两个静态字段,以实现统计已经实例化的男、女生数这一功能。在Main函数中实例化若干个学生,最终打印出男女生人数
具体的代码如下:
using System;
namespace 期中_编程题
{
class Person
{
public string name;
public char sex;
public Person() { }
public Person(string x, char y)
{
name = x;
sex = y;
}
}
class Student : Person
{
public string sno;
public static int males=0;
public static int females = 0;
public Student() { }
public Student(string x,string y,char z)
{
sno = x;
name = y;
sex = z;
if (z == '男')
{
males++;
}
if (z == '女')
{
females++;
}
}
}
class Program
{
static void Main(string[] args)
{
//下面输入三个学生的学号、姓名、性别并实例化三个学生
string sid = Console.ReadLine();//输入学号
string name = Console.ReadLine();//输入姓名
char sex = Convert.ToChar(Console.ReadLine());//输入性别
Student s1 = new Student(sid, name, sex);
sid = Console.ReadLine();
name = Console.ReadLine();
sex = Convert.ToChar(Console.ReadLine());
Student s2 = new Student(sid, name, sex);
sid = Console.ReadLine();
name = Console.ReadLine();
sex = Convert.ToChar(Console.ReadLine());
Student s3 = new Student(sid, name, sex);
//下面打印男女生人数统计
Console.WriteLine("男生数:{0},女生数:{1}", Student.males, Student.females);
}
}
}
运行的结果如图所示