花匠小林 2015-04-05 11:52 采纳率: 100%
浏览 1607
已采纳

请问这道题用C++怎么做?关于类的

建立一个person类,包含姓名、性别、年龄三个公有字段,另包含males、females两个公有静态字段成员,用来记录男、女的人数,建立一个teacher类和一个student类,这两个类都继承person类,teacher包含工号,工资字段,student包含学号,班级字段,在main函数里面增加几个学生对象和老师对象,然后统计男女总人数,并且分别打印所有所有教师和学生的信息。

  • 写回答

7条回答 默认 最新

  • gaoshao178 2015-04-05 12:57
    关注

    #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;
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值