花匠小林 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 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥60 SOL语句中Where查询中的 from to 语句能不能从小到大换成从大到小(标签-SQL)
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 请教一下c语言的代码里有一个地方不懂
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))