建立一個person類,包含姓名、性別、年齡三個公有字段,另包含males、females兩個公有靜態字段成員,用來記錄男、女的人數,建立一個teacher類和一個student類,這兩個類都繼承person類,teacher包含工號,工資字段,student包含學號,班級字段,在main函數裡面增加幾個學生對象和老師對象,然後統計男女總人數,並且分別打印所有所有教師和學生的信息。
#include
#include
using namespace std;
class Person
{
public:
string name;
string sex;
int age;
static int males;
static int females;
};
int Person::males = 0;
int Person::fmales = 0;
class Teacher: Person
{
public:
string workNum;
string salve;
Teacher(string name, string sex, int age, string workNum, string salve)
{
this->name = name;
this->sex = sex;
this->age = age;
this->workNum = workNum;
this->salve = salve;
if (this->sex == "nan")
{
males++;
}
else if (this->sex == "nv")
{
females++;
}
}
};
class Student: Person
{
public:
int stuNum;
int classNum;
Student(string name, string sex, int age, int stuNum, int classNum)
{
this->name = name;
this->sex = sex;
this->age = age;
this->stuNum= stuNum;
this->classNum= classNum;
if (this->sex == "nan")
{
males++;
}
else if (this->sex == "nv")
{
females++;
}
}
};
int main()
{
Student stu1("aa", "nan", 13, 1, 1);
Student stu2("bb", "nan", 14, 2, 2);
Teacher ter1("cc", "nan", 26, "001", "5000");
Teacher ter2("dd", "nv", 26, "007", "5000");
cout << "Student:" << endl;
cout << "name:" << stu1.name << "sex:" << stu1.sex << "age:" << stu1.age
<< "stuNum:" << stu1.stuNum << "classNum:" << stu1.classNum << endl;
cout << "name:" << stu2.name << "sex:" << stu2.sex << "age:" << stu2.age
<< "stuNum:" << stu2.stuNum << "classNum:" << stu2.classNum << endl;
cout << "Teacher:" << endl;
cout << "name:" << ter1.name << "sex:" << ter1.sex << "age:" << ter1.age
<< "workNum:" << ter1.stuNum << "salve:" << ter1.salve << endl;
cout << "name:" << ter2.name << "sex:" << ter2.sex << "age:" << ter2.age
<< "workNum:" << ter2.stuNum << "salve:" << ter2.salve << endl;
cout << "males:" << Person::males << endl;
cout << f"males:" << Person::fmales << endl;
return 0;
}